-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertInterval2.java
More file actions
59 lines (57 loc) · 1.47 KB
/
InsertInterval2.java
File metadata and controls
59 lines (57 loc) · 1.47 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
package mergeIntervals;
import java.util.ArrayList;
import java.util.List;
public class InsertInterval2 {
public List<Interval> insert(List<Interval> intervals, Interval newInterval){
List<Interval> result = new ArrayList<>();
if(intervals.isEmpty()){
result.add(newInterval);
return result;
}
int[] start = new int[intervals.size()];
int[] end = new int[intervals.size()];
for(int i = 0; i < intervals.size(); i++){
start[i] = intervals.get(i).start;
end[i] = intervals.get(i).end;
}
int beginValue = newInterval.start;
int endValue = newInterval.end;
int beginIndex = intervals.size();
for(int i = 0; i < intervals.size(); i++){
if(beginValue > end[i]){
result.add(new Interval(start[i], end[i]));
}
else{
beginIndex = i;
break;
}
}
if(beginIndex == intervals.size()){
result.add(newInterval);
return result;
}
if(beginValue >= start[beginIndex]){
beginValue = start[beginIndex];
}
int endIndex = intervals.size()-1;
for(int i = beginIndex; i < intervals.size(); i++){
if(endValue < start[i] ){
endIndex = i-1;
break;
}
}
if(endIndex != -1){
if(endValue <= end[endIndex]){
endValue = end[endIndex];
}
}
result.add(new Interval(beginValue, endValue));
if(endIndex == intervals.size()-1){
return result;
}
for(int i = endIndex+1; i < intervals.size(); i++){
result.add(intervals.get(i));
}
return result;
}
}