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"].
这道题开始做的比较混乱,看了大神的思路才得以理解。此题以nums[i]-1考虑结点,检查low和nums[i]-1的差值,如果为0,就是low+"",如果不为0,就是low+"->"+nums[i]-1;然后给low赋值成nums[i]+1.遍历完数组之后,检查low和upper的关系。此题一定要注意overflow问题,要定义成long型!!代码如下:
public class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
List<String> res= new ArrayList<>();
long low = lower;
long up =upper;
for(int n:nums){
long cur = (long)n-1;
if(low==cur) res.add(cur+"");
else if(low<cur) res.add(low+"->"+cur);
low = (long)n+1;
}
if(low<up) res.add(low+"->"+up);
else if(low==up) res.add(up+"");
return res;
}
}