-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path57.insert-interval.java
More file actions
65 lines (56 loc) · 2.27 KB
/
Copy path57.insert-interval.java
File metadata and controls
65 lines (56 loc) · 2.27 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
60
61
62
63
64
65
/*
* @lc app=leetcode id=57 lang=java
*
* [57] Insert Interval
*/
// @lc code=start
class Solution {
// Returns true if the intervals a and b have a common element.
boolean doesIntervalsOverlap(int[] a, int[] b) {
return Math.min(a[1], b[1]) - Math.max(a[0], b[0]) >= 0;
}
// Return the interval having all the elements of intervals a and b.
int[] mergeIntervals(int[] a, int[] b) {
int[] newInterval = { Math.min(a[0], b[0]), Math.max(a[1], b[1]) };
return newInterval;
}
// Insert the interval newInterval, into the list interval keeping the sorting
// order intact.
int[][] insertInterval(int[][] intervals, int[] newInterval) {
boolean isIntervalInserted = false;
List<int[]> list = new ArrayList<>(Arrays.asList(intervals));
for (int i = 0; i < intervals.length; i++) {
if (newInterval[0] < intervals[i][0]) {
// Found the position, insert the interval and break from the loop.
list.add(i, newInterval);
isIntervalInserted = true;
break;
}
}
// If there is no interval with a greater value of start value,
// then the interval must be inserted at the end of the list.
if (!isIntervalInserted) {
list.add(newInterval);
}
return list.toArray(new int[list.size()][2]);
}
public int[][] insert(int[][] intervals, int[] newInterval) {
// Insert the interval first before merge processing.
intervals = insertInterval(intervals, newInterval);
List<int[]> answer = new ArrayList<>();
for (int i = 0; i < intervals.length; i++) {
int[] currInterval = { intervals[i][0], intervals[i][1] };
// Merge until the list gets exhausted or no overlap is found.
while (i < intervals.length && doesIntervalsOverlap(currInterval, intervals[i])) {
currInterval = mergeIntervals(currInterval, intervals[i]);
i++;
}
// Decrement to ensure we don't skip the interval due to outer for-loop
// incrementing.
i--;
answer.add(currInterval);
}
return answer.toArray(new int[answer.size()][2]);
}
}
// @lc code=end