-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertInterval.java
More file actions
59 lines (50 loc) · 1.17 KB
/
InsertInterval.java
File metadata and controls
59 lines (50 loc) · 1.17 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
import java.util.*;
public class InsertInterval {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> list = new ArrayList<Interval>();
Interval thisInterval = newInterval;
boolean considerNewInterval = true;
for(int i =0; i<intervals.size(); i++)
{
Interval from = intervals.get(i);
if(considerNewInterval)
{
if(from.start > thisInterval.end || from.end < thisInterval.start)
{
if(thisInterval.start < from.start)
{
list.add(thisInterval);
considerNewInterval = false;
}
list.add(from);
}
else
{
thisInterval.start = Math.min(thisInterval.start, from.start);
thisInterval.end = Math.max(thisInterval.end, from.end);
}
}
else
{
list.add(from);
}
}
if(list.size() == 0 ||list.get(list.size()-1).start< thisInterval.start)
{
list.add(thisInterval);
}
return list;
}
public class Interval {
int start;
int end;
Interval() { start = 0; end = 0; }
Interval(int s, int e) { start = s; end = e; }
}
}