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 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] |
Example 2:
1 | Input: intervals = [[1,4],[4,5]] |
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 | public int[][] merge(int[][] intervals) { |
LeetCode 56. Merge Intervals