You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in 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 smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges.
class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
// two pointers,i & j, for loop j (check nums.length > 2), if [j] == [j-1]+1 continue, else handle
// left, right, if l == r, add only l. else add l->r.
// handle first and last.
List<String> res = new ArrayList<String>();
int n = nums.length;
// edge cases
if (n == 0) {
addRange(res, lower, upper);
return res;
}
// first one
if (lower < nums[0]) {
addRange(res, lower, nums[0]-1);
}
// body
if (n >= 2) {
for (int i = 1; i < n; i++) {
long diff = (long)nums[i] - (long)nums[i-1];
if (diff == 1) continue;
// stop, check value
if (diff >= 2) {
addRange(res, nums[i-1]+1, nums[i]-1);
}
}
}
// last
if (nums[n-1] < upper) {
addRange(res, nums[n-1]+1, upper);
}
return res;
}
private void addRange(List<String> res, int l, int r) {
if (l == r) {
res.add(l+"");
} else if (l < r) {
res.add(l+"->"+r);
}
}
}