You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are within the inclusive range.
A number x is considered missing if x is in the range [lower, upper] and x is not in nums.
Return the shortest sorted list of ranges that exactly covers all the missing numbers. That is, no element of nums is included in any of the ranges, and each missing number is covered by one of the ranges.
classSolution {
public List<List<Integer>>findMissingRanges(int[] nums, int lower, int upper) {
int n = nums.length;
List<List<Integer>> ans =new ArrayList<>();
if (n == 0) {
ans.add(List.of(lower, upper));
return ans;
}
// Check for missing range before the first elementif (nums[0]> lower) {
ans.add(List.of(lower, nums[0]- 1));
}
// Check for missing ranges between consecutive elementsfor (int i = 1; i < n; ++i) {
if (nums[i]- nums[i - 1]> 1) {
ans.add(List.of(nums[i - 1]+ 1, nums[i]- 1));
}
}
// Check for missing range after the last elementif (nums[n - 1]< upper) {
ans.add(List.of(nums[n - 1]+ 1, upper));
}
return ans;
}
}
classSolution:
deffindMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[List[int]]:
n: int = len(nums)
ans: List[List[int]] = []
if n ==0:
ans.append([lower, upper])
return ans
# Check for missing range before the first elementif nums[0] > lower:
ans.append([lower, nums[0] -1])
# Check for missing ranges between consecutive elementsfor i in range(1, n):
if nums[i] - nums[i -1] >1:
ans.append([nums[i -1] +1, nums[i] -1])
# Check for missing range after the last elementif nums[-1] < upper:
ans.append([nums[-1] +1, upper])
return ans