codeTop100题(31)56. 合并区间

103 阅读1分钟

1. 题目

56. 合并区间

2. 分析

image.png

本题需要找到重合的部分,并作为一个大数组,从题目中给出的case来看,我们只需要依次遍历,如果重合,左边取小的,右边取大的就行了。

但是有一个问题:假如说给的case是无序 的咋整,例如[[99,100],[1,2][99,112]]

我们可以基于子数字的第一个数字排序一下。

3. 代码

public int[][] merge(int[][] intervals) {

    PriorityQueue<int[]> priorityQueue = new PriorityQueue<>(new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return o1[0] - o2[0];
        }
    });
    for (int[] interval : intervals) {
        priorityQueue.offer(interval);
    }

    int[] temp = null;
    List<int[]> list = new ArrayList<>();
    while (!priorityQueue.isEmpty()) {
        //temp 为空
        if (null == temp) {
            temp = priorityQueue.poll();
            continue;
        }
        //能合并
        int[] poll = priorityQueue.poll();
        if (temp[1] >= poll[0]) {
            temp = new int[]{Math.min(temp[0], poll[0]), Math.max(temp[1], poll[1])};
        } else {
            list.add(temp);
            temp = poll;
        }
    }
    return list.toArray(new int[][]{});
}