offer2-74


以数组 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].

示例 2:

输入:intervals = [[1,4],[4,5]]
输出:[[1,5]]
解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。

提示:

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

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int[][] merge(int[][] intervals) {
        PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] != o2[0]) {
                    return o1[0] - o2[0];
                } else {
                    return o2[1] - o2[1];
                }
            }
        });

        List<int[]> resultList = new ArrayList<>();
        for (int[] interval : intervals) {
            pq.add(interval);
        }

        while (!pq.isEmpty()) {
            int[] first = pq.poll();

            if (pq.isEmpty()) {
                resultList.add(first);
                break;
            }

            if (isCross(first, pq.peek())) {
                int[] second = pq.poll();
                int[] merge = new int[2];
                merge[0] = first[0];
                merge[1] = first[1] > second[1] ? first[1] : second[1];
                pq.add(merge);
            } else {
                resultList.add(first);
            }
        }

        return resultList.toArray(new int[resultList.size()][2]);
    }

    private boolean isCross(int[] o1, int[] o2) {
        int maxStart = Math.max(o1[0], o2[0]);
        int minEnd = Math.min(o1[1], o2[1]);
        return maxStart <= minEnd;
    }

}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !