163. Missing Ranges
給定一個包含範圍 [lower, upper] 以及一個已排序且唯一的整數數組 nums,其中所有元素都在該範圍內。
如果數字 x 在範圍 [lower, upper] 內並且不在 nums 中,則 x 被認為是缺失的。
返回最短的已排序的範圍列表,這些範圍恰好涵蓋了所有缺失的數字。也就是說,nums 中的元素不包含在任何範圍內,且每個缺失的數字都被其中一個範圍涵蓋。
範例 :
輸入:nums = [0,1,3,50,75], lower = 0, upper = 99
輸出:[[2,2],[4,49],[51,74],[76,99]]
解釋:範圍是:[2,2]
[4,49]
[51,74]
[76,99]
Python
from typing import List
class Solution:
def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[List[int]]:
result = []
prev = lower - 1
for i in range(len(nums) + 1):
curr = nums[i] if i < len(nums) else upper + 1
if curr - prev > 1:
result.append([prev + 1, curr - 1])
prev = curr
return result
16.5MB, 37ms
C++
class Solution {
public:
vector<vector<int>> findMissingRanges(vector<int>& nums, int lower, int upper) {
vector<vector<int>> result;
int prev = lower - 1;
for (int i = 0; i <= nums.size(); ++i) {
int curr = (i < nums.size()) ? nums[i] : upper + 1;
if (curr - prev > 1) {
result.push_back({prev + 1, curr - 1});
}
prev = curr;
}
return result;
}
};
8.24MB, 0ms
Javascript
/**
* @param {number[]} nums
* @param {number} lower
* @param {number} upper
* @return {number[][]}
*/
var findMissingRanges = function(nums, lower, upper) {
let result = [];
let prev = lower - 1;
// Add upper + 1 to handle the case where upper is missing
nums.push(upper + 1);
for (let curr of nums) {
if (curr - prev > 1) {
result.push([Math.max(lower, prev + 1), Math.min(upper, curr - 1)]);
}
prev = curr;
}
return result;
};
48.58MB, 55ms