[LeetCode] Missing Ranges

163. Missing Ranges

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<vector<int>> findMissingRanges(vector<int>& nums, int lower, int upper) {
nums.push_back(INT_MAX);
nums.push_back(INT_MIN);
sort(begin(nums),end(nums));
vector<vector<int>> res;
for(int i = 0; i < nums.size() - 1; i++) {
int le = max(lower, nums[i] + 1), ri = min(upper,nums[i+1] - 1);
if(le > ri) continue;
res.push_back({le,ri});
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/15/PS/LeetCode/missing-ranges/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.