163. Missing Ranges
2021-08-11 本文已影响0人
jluemmmm
给定上下限,确定有序数组中缺失的区间。
- 时间复杂度O(N),空间复杂度O(1)
- Runtime: 76 ms, faster than 35.71%
- Memory Usage: 38.7 MB, less than 61.90%
/**
* @param {number[]} nums
* @param {number} lower
* @param {number} upper
* @return {string[]}
*/
var findMissingRanges = function(nums, lower, upper) {
let res = []
let prev = lower - 1;
for (let i = 0; i <= nums.length; i++) {
let cur = (i < nums.length ? nums[i] : upper + 1);
if(prev + 1 <= cur - 1) {
res.push(formatRange(prev + 1, cur - 1));
}
prev = cur;
}
return res;
};
var formatRange = function (lower, upper) {
if (lower === upper) {
return String(lower);
}
return String(lower) + '->' + String(upper);
}