Missing Ranges
Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges.
Example
Example 1
Input:
nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99
Output:
["2", "4->49", "51->74", "76->99"]
Explanation:
in range[0,99],the missing range includes:range[2,2],range[4,49],range[51,74] and range[76,99]
Example 2
Input:
nums = [0, 1, 2, 3, 7], lower = 0 and upper = 7
Output:
["4->6"]
Explanation:
in range[0,7],the missing range include range[4,6]
public class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
List<String> ans = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
// Handling outer limits
if (i == 0) {
long l = lower;
l--;
String interval = interval(l, (long) nums[i]);
if (interval.length() != 0)
ans.add(interval);
}
if (i == nums.length - 1) {
long u = upper;
u++;
String interval = interval((long) nums[i], u);
if (interval.length() != 0)
ans.add(interval);
}
// Handling array intervals
if (i != nums.length - 1) {
String interval = interval((long) nums[i], (long) nums[i + 1]);
if (interval.length() != 0)
ans.add(interval);
}
}
if (nums.length == 0) {
long l = lower, u = upper;
l--;
u++;
String interval = interval(l, u);
if (interval.length() != 0)
ans.add(interval);
}
return ans;
}
public String interval(long start, long end) {
if (end - start == 2)
return Long.toString(start + 1);
else if (end - start > 2) {
String interval = Long.toString(start + 1) + "->" + Long.toString(end - 1);
return interval;
} else
return "";
}
}
Last updated