LeetCode 163 Missing Ranges
Given a sorted integer array where the range of elements are [lower, upper] inclusive, 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"].
这题的follow up个人感觉会非常复杂。。。如果需要考虑给出的[lower, upper]区间否是完全包含sorted array。。。
不过这里说了ranges是[lower, upper] inclusive,所以只考虑sorted array完全在该范围内的情况,因此需要重点考虑的是lower和upper两头的case。
自己写了一下代码比较繁琐。。。
代码:
public class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
int n = nums.length;
int st = lower, i = 0;
List<String> ranges = new ArrayList<>();
if (n == 0) {
String str = "";
if (lower == upper)
str = "" + lower;
else
str = lower + "->" + upper;
ranges.add(str);
return ranges;
}
while (i < n) {
if (st < nums[i]) {
String str = "";
if (st == nums[i]-1)
str = "" + st;
else
str = st + "->" + (nums[i]-1);
ranges.add(str);
}
st = nums[i]+1;
i++;
}
if (st <= upper) {
String str = "";
if (st == upper)
str = "" + st;
else
str = st + "->" + (upper);
ranges.add(str);
}
return ranges;
}
}