LeetCode 56. Merge Intervals

Question

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Example 1:

1
2
3
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

1
2
3
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Constraints:

  • 1 <= intervals.length <= 104
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 104

Source: https://leetcode.com/problems/merge-intervals/

Solution

For interval problems, sorting the interval array by start is usually a cracking direction.

For sorted interval array, if prev.end < curr.start, there is no overlap between these two intervals Otherwise, they are overlapped.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public int[][] merge(int[][] intervals) {
// sort by the start in ascending order
Arrays.sort(intervals, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0];
}
});
Deque<int[]> merged = new LinkedList<>();
merged.add(intervals[0]);
for (int[] interval : intervals) {
int[] last = merged.getLast();
if (last[1] < interval[0]) {
merged.addLast(interval);
} else { // merge
last[1] = Math.max(last[1], interval[1]);
}
}
int[][] result = new int[merged.size()][];
merged.toArray(result);
return result;
}
Author

Weihao Ye

Posted on

2022-01-12

Updated on

2022-01-18

Licensed under