以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间。
示例 1:
输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
输出:[[1,6],[8,10],[15,18]]
解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
class Solution { public int[][] merge(int[][] intervals) { if (intervals == null || intervals.length == 1) { return intervals; } PriorityQueue<Node> minQueue = new PriorityQueue<>((a, b) -> a.start - b.start); for (int i = 0; i < intervals.length; i++) { minQueue.add(new Node(intervals[i][0], intervals[i][1])); } int[] flag = new int[2]; Node curNode = minQueue.poll(); flag[0] = curNode.start; flag[1] = curNode.end; int leftMin = flag[0]; int rightMax = flag[1]; PriorityQueue<Node> queue = new PriorityQueue<>((a, b) -> a.start - b.start); while (!minQueue.isEmpty()) { Node cur = minQueue.poll(); if (flag[1] >= cur.start) { leftMin = Math.min(leftMin, cur.start); rightMax = Math.max(rightMax, cur.end); flag[0] = leftMin; flag[1] = rightMax; } else if (cur.end <= rightMax) { continue; } else { queue.add(new Node(leftMin, rightMax)); flag[0] = cur.start; flag[1] = cur.end; leftMin = flag[0]; rightMax = flag[1]; } } queue.add(new Node(leftMin, rightMax)); int[][] res = new int[queue.size()][2]; int index = 0; while (!queue.isEmpty()) { Node cur = queue.poll(); res[index][0] = cur.start; res[index][1] = cur.end; index++; } return res; } public class Node { public int start; public int end; public Node(int s, int e) { this.start = s; this.end = e; } } } }