My PriorityQueue Solution:

class Solution {
    public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
        PriorityQueue<int[]> pq1 = new PriorityQueue<>((a,b)->a[0]-b[0]);
        PriorityQueue<int[]> pq2 = new PriorityQueue<>((a,b)->a[0]-b[0]);
        for(int[] list:firstList){
            pq1.offer(list);
        }
        
         for(int[] list:secondList){
            pq2.offer(list);
        }
        
        List<int[]> list = new ArrayList<>();
        while(!pq1.isEmpty()&&!pq2.isEmpty()){
            int[] time1= pq1.poll();
            int[] time2= pq2.poll();
            
            int start = Math.max(time1[0], time2[0]);
            int end = Math.min(time1[1], time2[1]);
            
            if(start<=end)
            list.add(new int[]{start, end});
            
            if(time1[1]==end)
                pq2.offer(time2);
            else if(time2[1]==end)
                pq1.offer(time1);
        }
        
        int[][] res = new int[list.size()][2];
        for(int i=0;i<list.size();i++){
            res[i]=list.get(i);
        }
        return res;
    }
}

Since the array is sorted already, we don't have to user PriorityQueue:

class Solution {
    public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
        int i=0, j=0;
        List<int[]> list = new ArrayList<>();
        while(i<firstList.length && j<secondList.length){
            int[] time1= firstList[i];
            int[] time2= secondList[j];
            
            int start = Math.max(time1[0], time2[0]);
            int end = Math.min(time1[1], time2[1]);
            
            if(start<=end)
            list.add(new int[]{start, end});
            
            if(time1[1]==end)
                i++;
            else if(time2[1]==end)
                j++;
        }
        return list.toArray(new int[list.size()][2]);
    }
}

 

posted on 2022-04-09 13:16  阳光明媚的菲越  阅读(18)  评论(0编辑  收藏  举报