美文网首页
163. Missing Ranges

163. Missing Ranges

作者: jluemmmm | 来源:发表于2021-08-11 10:29 被阅读0次

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

    • 时间复杂度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);
    }
    

    相关文章

      网友评论

          本文标题:163. Missing Ranges

          本文链接:https://www.haomeiwen.com/subject/qzgqbltx.html