forked from hijiangtao/LeetCode-with-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathres.js
34 lines (30 loc) · 705 Bytes
/
res.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* @param {number[]} nums
* @return {string[]}
*/
var summaryRanges = function(nums) {
let len = nums.length;
if (!len) return [];
let res = [];
let start = null, end = null;
for (let i = 0; i < len; i++) {
const e = nums[i];
if (start === null) {
start = nums[i];
end = nums[i];
} else if (e === end + 1) {
end = e;
} else {
res.push(getResStr(start, end));
start = e;
end = e;
}
}
if (!res.length || res[res.length-1] !== getResStr(start, end)) {
res.push(getResStr(start, end));
}
return res;
};
const getResStr = (start, end) => {
return start === end ? `${start}` : `${start}->${end === null ? start : end}`;
}