其他分享
首页 > 其他分享> > 986. Interval List Intersections

986. Interval List Intersections

作者:互联网

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]);
    }
}

 

标签:int,list,Interval,986,PriorityQueue,pq1,pq2,new,List
来源: https://www.cnblogs.com/feiflytech/p/16121656.html