Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathMissing Ranges.java
More file actions
Latest commit
executable file
·62 lines (49 loc) · 1.66 KB
/
Copy pathMissing Ranges.java
File metadata and controls
executable file
·62 lines (49 loc) · 1.66 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
M
tags: Array
#### BasicImplementation
- O(n)
- 两个pointer, 每次计较prev和curr之间的部分.
- 然后prev = curr,向前移动一格
- TODO: checktheedgecaseandmakesuremax/minof int arechecked
```
/*
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"].
Tags: Array
Similar Problems: (E) Summary Ranges
*/
/*
Attempt2, Thoughts:
Use two pointer to mark the prev and curr value, then verify the range in between.
matching conditoin: prev +2 >= curr.
That is,
1,...,3
1. When print range: print the missing [x,y]
2. missing x = prev+1, missing y = curr - 1;
3. Make sure prev represents the consecutive integer before missing x.
*/
publicclassSolution {
publicList<String> findMissingRanges(int[] nums, intlower, intupper) {
List<String> rst = newArrayList<String>();
if (nums == null || nums.length == 0) {//Though, also covered in the for
rst.add(printRange(lower, upper));
returnrst;
} elseif (lower > upper) {
returnrst;
}
intprev = lower - 1;
intcurr;
for (inti = 0; i <= nums.length; i++) {
curr = (i == nums.length) ? upper + 1 : nums[i];
if (prev + 2 <= curr) {
rst.add(printRange(prev + 1, curr - 1));
}
prev = curr;
}
returnrst;
}
publicStringprintRange(intfrom, intto) {
return (from == to) ? String.valueOf(from) : from + "->" + to;
}
}
```