-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntervalInsertion.java
More file actions
56 lines (48 loc) · 1.74 KB
/
IntervalInsertion.java
File metadata and controls
56 lines (48 loc) · 1.74 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
package intervals;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IntervalInsertion {
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
if (intervals.isEmpty()) intervals.add(newInterval);
int pos = binarySearch(intervals, newInterval.start);
pos = pos < 0 ? -pos - 1 : pos;
pos = pos - 1 < 0 ? pos : pos - 1;
Iterator<Interval> it = intervals.subList(pos, intervals.size()).iterator();
int start = newInterval.start;
int end = newInterval.end;
while (it.hasNext()) {
Interval cur = it.next();
if (cur.start > end) break;
if (start > cur.end) {
pos++;
continue;
}
start = Math.min(start, cur.start);
end = Math.max(end, cur.end);
it.remove();
}
intervals.add(pos, new Interval(start, end));
return intervals;
}
private int binarySearch(List<Interval> intervals, int start) {
if (intervals.isEmpty()) return -1;
int lo = 0, hi = intervals.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (start == intervals.get(mid).start) return mid;
else if (start < intervals.get(mid).start) hi = mid - 1;
else lo = mid + 1;
}
return -lo - 1;
}
public static void main(String[] args) {
List<Interval> list = new ArrayList<>();
list.add(new Interval(1, 3));
list.add(new Interval(6, 9));
new IntervalInsertion().insert(list, new Interval(2, 5));
for (Interval interval : list) {
System.out.println(interval.toString());
}
}
}