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"].
思路:
查看每個數(shù)字和上一個數(shù)字中是否需要補區(qū)間压昼,第一個數(shù)字需要和lower做比較拓售,最后一個數(shù)字還要和upper做一次比較。
此題坑較多:比如low和up相同蜻直,數(shù)組為空的case校仑;low和up是int類型的最小和最大值的情況佣赖,此時用num[i] - num[i-1]就會有溢出。
public static List<String> findMissingRanges(int[] nums, int lower, int upper) {
List<String> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
String range = "";
if (lower == upper) {
range = String.valueOf(lower);
} else {
range = String.valueOf(lower) + "->" + String.valueOf(upper);
}
//String range = String.valueOf(lower) + "->" + String.valueOf(upper);//bug
res.add(range);
return res;
}
for (int i = 0; i < nums.length; i++) {
String range = "";
//if (i == 0 && nums[i] > lower) {//bug//第一個和lower比
if (i == 0) {//第一個和lower比
if (nums[i] > lower) {
if (nums[i] - 1 == lower) {
range = String.valueOf(lower);
} else {
range = String.valueOf(lower) + "->" + String.valueOf(nums[i] - 1);
}
}
} else {
long diff = (long)nums[i] - (long)nums[i-1];
System.out.println(diff);
if (diff == 2) {//其余的和前一個比
range = String.valueOf(nums[i] - 1);
} else if (diff > 2) {
range = String.valueOf(nums[i-1] + 1) + "->" + String.valueOf(nums[i] - 1);
}
}
if (!range.equals("")) {
res.add(range);
}
//res.add(range);//bug 會向res重復(fù)add range
if (i == nums.length - 1 && nums[i] < upper) {//最后一個再和upper比一次
if (upper - 1 == nums[i]) {
range = String.valueOf(upper);
} else {
range = String.valueOf(nums[i] + 1) + "->" + String.valueOf(upper);
}
res.add(range);
}
//res.add(range); //bug 會向res重復(fù)add range
}
return res;
}