forked from ganjingcatherine/Lintcode_HighFreq
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path30.insert-interval.java
More file actions
47 lines (41 loc) · 1.18 KB
/
30.insert-interval.java
File metadata and controls
47 lines (41 loc) · 1.18 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
/**
* Definition of Interval:
* public classs Interval {
* int start, end;
* Interval(int start, int end) {
* this.start = start;
* this.end = end;
* }
*/
public class Solution {
/*
* @param intervals: Sorted interval list.
* @param newInterval: new interval.
* @return: A new interval list.
*/
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
if (intervals == null || newInterval == null) {
return intervals;
}
// Search place to insert
int i;
for (i = 0; i < intervals.size(); i++) {
if (intervals.get(i).start >= newInterval.start) {
break;
}
}
intervals.add(i, newInterval);
// Merge intervals
List<Interval> ans = new ArrayList<>();
Interval last = null;
for (Interval item : intervals) {
if (last == null || last.end < item.start) {
ans.add(item);
last = item;
} else {
last.end = Math.max(last.end, item.end);
}
}
return ans;
}
}