-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOverlappingIntervals.java
34 lines (31 loc) · 1.08 KB
/
OverlappingIntervals.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
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> newList = new LinkedList<>();
// Add Non-Overlapping Intervals
int i = 0;
for(int []interval: intervals){
if(interval[1] < newInterval[0]){
newList.add(interval);
i++;
}
else
break;
}
// Merge new Interval with overlapping intervals
while(i < intervals.length && intervals[i][0] <= newInterval[1]){
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
newList.add(newInterval);
// Add rest of the intervals
while(i < intervals.length)
newList.add(intervals[i++]);
return newList.stream().toArray(int[][]::new);
}
boolean isOverlap(int[] interval, int[] newInterval){
if(interval[0] > newInterval[1] || interval[1] < newInterval[0])
return false;
return true;
}
}