-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leetcode057.java
36 lines (31 loc) · 1.13 KB
/
Leetcode057.java
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
package test;
//将新的interval插入并合并相同项
public class Leetcode057 {
//用ans存储答案,比较interval,若不重复,则排入ans,否则更新newInterval,进行下一次比较
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> ans = new ArrayList<Interval>();
int count = intervals.size();
if (count == 0) {
ans.add(newInterval);
return ans;
}
for (int i=0; i<intervals.size(); i++) {
Interval s = intervals.get(i);
if (newInterval.start > s.end)
ans.add(s);
else {
if (newInterval.end >= s.start) {
newInterval.start = newInterval.start < s.start ? newInterval.start : s.start;
newInterval.end = newInterval.end > s.end ? newInterval.end : s.end;
} else {
count = i;
break;
}
}
}
ans.add(newInterval);
for (int i=count; i<intervals.size(); i++)
ans.add(intervals.get(i));
return ans;
}
}