forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTonyKim9401.java
More file actions
32 lines (26 loc) · 853 Bytes
/
TonyKim9401.java
File metadata and controls
32 lines (26 loc) · 853 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
// TC: O(n)
// must retrieve all elements
// SC: O(n)
// need the same size of memory space in the worst case
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> output = new ArrayList<>();
int i = 0;
int n = intervals.length;
while (i < n && intervals[i][1] < newInterval[0]) {
output.add(intervals[i]);
i += 1;
}
while (i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i += 1;
}
output.add(newInterval);
while (i < n) {
output.add(intervals[i]);
i += 1;
}
return output.toArray(new int[output.size()][]);
}
}