-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertInterval.java
More file actions
53 lines (51 loc) · 1.67 KB
/
InsertInterval.java
File metadata and controls
53 lines (51 loc) · 1.67 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
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class InsertInterval {
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
int i=0;
for(; i<intervals.size(); i++) {
if(intervals.get(i).start<newInterval.start){
if(intervals.get(i).end<newInterval.start) {
continue;
}
else {
intervals.get(i).end = Math.max(intervals.get(i).end, newInterval.end);
break;
}
} else {
if(intervals.get(i).start>newInterval.end) {
intervals.add(i, newInterval);
return intervals;
}
else {
intervals.get(i).start = newInterval.start;
intervals.get(i).end = Math.max(intervals.get(i).end, newInterval.end);
break;
}
}
}
if(i==intervals.size()) {
intervals.add(newInterval);
return intervals;
}
Interval prev = intervals.get(i);
int currentIndex = i++;
for(;i<intervals.size(); i++) {
Interval curr = intervals.get(i);
if(prev.end>= curr.start) {
prev.end = Math.max(prev.end, curr.end);
} else {
intervals.set(++currentIndex, curr);
prev = curr;
}
}
return intervals.subList(0, currentIndex+1);
}
}