05 August 2008
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
List<String> list = new ArrayList<String>();
if(nums == null) return list;
int n = nums.length;
for(int i = 0; i <= n; i++) {
int lt = (i == 0) ? lower : nums[i - 1] + 1;
int gt = (i == n) ? upper : nums[i] - 1;
addRange(list, lt, gt);
}
return list;
}
private void addRange(List<String> list, int lo, int hi) {
if(lo > hi) return;
else if(lo == hi) list.add(String.valueOf(lo));
else list.add(lo + "->" + hi);
}
Java8
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
List<String> res = new ArrayList<>();
for(int i : nums) {
if(i > lower) res.add(lower+((i-1 > lower)?"->"+(i-1):""));
if(i == upper) return res; // Avoid overflow
lower = i+1;
}
if(lower <= upper) res.add(lower + ((upper > lower)?"->"+(upper):""));
return res;
}
}