-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathMergeIntervals.java
More file actions
43 lines (35 loc) · 1004 Bytes
/
MergeIntervals.java
File metadata and controls
43 lines (35 loc) · 1004 Bytes
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
package Array;
import java.util.ArrayList;
/**
* Author - archit.s
* Date - 06/09/18
* Time - 12:04 PM
*/
public class MergeIntervals {
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
ArrayList<Interval> r = new ArrayList<>();
Interval prev = newInterval;
Interval cur = new Interval(-1,-1);
for(int i=0;i<intervals.size();i++){
cur = intervals.get(i);
if(prev.start < cur.start){
if(prev.end < cur.start){
r.add(prev);
prev = cur;
}
else{
prev.end = Math.max(prev.end, cur.end);
}
}
else if(prev.start <= cur.end){
prev.start = cur.start;
prev.end = Math.max(prev.end, cur.end);
}
else{
r.add(cur);
}
}
r.add(prev);
return r;
}
}