forked from kdn251/interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmissingRanges.java
More file actions
46 lines (24 loc) · 1.12 KB
/
missingRanges.java
File metadata and controls
46 lines (24 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 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"].
public class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i <= nums.length; i++) {
long start = i == 0 ? lower : (long)nums[i - 1] + 1;
long end = i == nums.length ? upper : (long)nums[i] - 1;
addMissing(result, start, end);
}
return result;
}
void addMissing(ArrayList<String> result, long start, long end) {
if(start > end) {
return;
}
else if(start == end) {
result.add(start + "");
}
else {
result.add(start + "->" + end);
}
}
}