My PriorityQueue Java Solution


  • 0
    Z
    public class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            if(intervals.size()<=1) return intervals;
            List<Interval> res = new ArrayList<>();
            PriorityQueue<Interval> q = new PriorityQueue<Interval>(intervals.size(),new Comparator<Interval>(){
                public int compare(Interval a,Interval b){
                    return a.start-b.start;
                }
            });
            for(Interval i:intervals){
                q.offer(i);
            }
            Interval val = q.poll();
            int start  = val.start;
            int end = val.end;
            while(!q.isEmpty()){
                Interval i = q.poll();
                if(i.start<=end){
                    end = Math.max(end,i.end);
                }else{
                    res.add(new Interval(start,end));
                    start = i.start;
                    end = i.end;
                }
            }
            res.add(new Interval(start,end));
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.