163. Missing Ranges

2021-08-11  本文已影响0人  jluemmmm

给定上下限,确定有序数组中缺失的区间。

/**
 * @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);
}
上一篇下一篇

猜你喜欢

热点阅读