-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsert-Interval.java
31 lines (28 loc) · 974 Bytes
/
Insert-Interval.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
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> ans = new ArrayList<>();
boolean inserted = false;
for(int i = 0; i < intervals.length; i++){
// end of interval < start of new
if(intervals[i][1] < newInterval[0]){
ans.add(intervals[i]);
}
// start of interval > end of new
else if(intervals[i][0] > newInterval[1]){
if(inserted == false){
ans.add(newInterval);
inserted = true;
}
ans.add(intervals[i]);
}
else{
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
}
}
if(inserted == false){
ans.add(newInterval);
}
return ans.toArray(new int[0][]);
}
}