Summary Ranges
Description
Given a sorted integer array without duplicates, return the summary of its ranges.
Example 1:
Input: [0,1,2,4,5,7] Output: ["0->2","4->5","7"] Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:
Input: [0,2,3,4,6,8,9] Output: ["0","2->4","6","8->9"] Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
Solution(javascript)
/*
* @lc app=leetcode id=228 lang=javascript
*
* [228] Summary Ranges
*/
// @lc code=start
/**
* @param {number[]} nums
* @return {string[]}
*/
const summaryRanges = function (nums) {
let start = null
const result = []
for (let i = 0; i < nums.length; i++) {
if (start === null) {
start = nums[i]
}
if (nums[i] === nums[i + 1] - 1) {
continue
}
if (nums[i] === start) {
result.push(nums[i].toString())
start = null
} else {
result.push(`${start}->${nums[i]}`)
start = null
}
}
return result
}
// @lc code=end