Skip to content

Commit acfd52c

Browse files
committed
Add solution #228
1 parent 71c1ccd commit acfd52c

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@
197197
220|[Contains Duplicate III](./0220-contains-duplicate-iii.js)|Hard|
198198
225|[Implement Stack using Queues](./0225-implement-stack-using-queues.js)|Easy|
199199
226|[Invert Binary Tree](./0226-invert-binary-tree.js)|Easy|
200+
228|[Summary Ranges](./0228-summary-ranges.js)|Easy|
200201
229|[Majority Element II](./0229-majority-element-ii.js)|Medium|
201202
231|[Power of Two](./0231-power-of-two.js)|Easy|
202203
232|[Implement Queue using Stacks](./0232-implement-queue-using-stacks.js)|Easy|

solutions/0228-summary-ranges.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 228. Summary Ranges
3+
* https://leetcode.com/problems/summary-ranges/
4+
* Difficulty: Easy
5+
*
6+
* You are given a sorted unique integer array nums.
7+
*
8+
* A range [a,b] is the set of all integers from a to b (inclusive).
9+
*
10+
* Return the smallest sorted list of ranges that cover all the numbers in the
11+
* array exactly. That is, each element of nums is covered by exactly one of
12+
* the ranges, and there is no integer x such that x is in one of the ranges
13+
* but not in nums.
14+
*
15+
* Each range [a,b] in the list should be output as:
16+
* - "a->b" if a != b
17+
* - "a" if a == b
18+
*/
19+
20+
/**
21+
* @param {number[]} nums
22+
* @return {string[]}
23+
*/
24+
var summaryRanges = function(nums) {
25+
const result = [];
26+
for (let i = 0, n = nums[0]; i < nums.length; i++) {
27+
if (nums[i] + 1 !== nums[i + 1]) {
28+
result.push(nums[i] === n ? `${n}` : `${n}->${nums[i]}`);
29+
n = nums[i + 1];
30+
}
31+
}
32+
return result;
33+
};

0 commit comments

Comments
 (0)