Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
For example, given [0, 1, 3, 50, 75]
, lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]
.
一刷
题解:如果当前值与lower相等,那么lower和i都要自加,找到下一个缺失的。比如lower=1, nums = {1,2,3}, 缺失的为4
public class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
List<String> res = new ArrayList<>();
if(nums.length==0){
res.add(getRange(lower, upper));
return res;
}
int next = lower;
for(int i=0; i<nums.length; i++){
if(nums[i]<next) continue;
if(i+1<nums.length && nums[i] == nums[i+1]) continue;
if(nums[i] == next){//increase the lower, the next was missed
next++;
continue;
}
res.add(getRange(next, nums[i]-1));
next = nums[i]+1;
}
if(next == Integer.MIN_VALUE && upper==Integer.MAX_VALUE) return res;
if(next<=upper) res.add(getRange(next, upper));
return res;
}
private String getRange(int a, int b){
if(a == b) return String.valueOf(a);
else return String.format("%d->%d", a, b);
}
}