Missing Ranges
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"].
Solution
public class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
if (lower > upper) return new ArrayList<>();
List<String> result = new ArrayList<>();
if (nums.length == 0) {
String temp = toRange(lower, upper + 1);
result.add(temp);
return result;
}
if (lower < nums[0]) {
String temp = toRange(lower, nums[0]);
if (!temp.equals("")) {
result.add(toRange(lower, nums[0]));
}
}
for (int i = 1; i < nums.length; i++) {
String temp;
if (nums[i] <= upper) {
temp = toRange(nums[i - 1] + 1, nums[i]);
} else {
temp = toRange(nums[i - 1] + 1, upper);
}
if (!temp.equals("")) {
result.add(temp);
}
}
if (nums[nums.length - 1] < upper) {
String temp = toRange(nums[nums.length - 1] + 1, upper+1);
if (!temp.equals("")) {
result.add(temp);
}
}
return result;
}
private String toRange(int start, int end) {
if (end <= start) {
return "";
}
if (end - start > 1) {
return start + "->" + (end - 1);
} else {
return String.valueOf(start);
}
}
}