My PriorityQueue Solution:

class Solution {
    public int[][] merge(int[][] intervals) {
        PriorityQueue<int[]> queue = new PriorityQueue<>((a,b)->a[0]-b[0]);
        for(int[] inter: intervals){
            queue.offer(inter);
        }
        List<int[]> res = new ArrayList<>();
        while(!queue.isEmpty()){
            int[] first = queue.poll();
            if(!queue.isEmpty()){
                int[] next = queue.poll();
                if(first[1]>=next[0]){
                    queue.offer(new  int[]{first[0], Math.max(first[1], next[1])});
                }
                else{
                    res.add(first);
                    queue.offer(next);
                }
            }else{
                res.add(first);
            }
        }
        
        return res.toArray()
        
        int[][] resA = new int[res.size()][2];
        for(int i=0;i<res.size();i++){
            resA[i]=res.get(i);
        }
        return resA;
    }
}

 

posted on 2022-04-07 06:33  阳光明媚的菲越  阅读(24)  评论(0编辑  收藏  举报