13ms Java PriorityQueue


  • 1
    A
    public class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            if ( intervals.isEmpty() ) { return intervals; }
            PriorityQueue<Interval> sorted = new PriorityQueue<>(intervals.size(), (i1, i2) -> i1.start - i2.start);
            sorted.addAll(intervals);
    
            List<Interval> result = new ArrayList<>();
            Interval current = sorted.poll();
            int mergedStart = current.start;
            int mergedEnd = current.end;
            while ( !sorted.isEmpty() ) {
                current = sorted.poll();
                if ( current.start <= mergedEnd ) {
                    mergedEnd = Math.max(mergedEnd, current.end);
                } else {
                    result.add(new Interval(mergedStart, mergedEnd));
                    mergedStart = current.start;
                    mergedEnd = current.end;
                }
            }
            result.add(new Interval(mergedStart, mergedEnd));
            return result;
        }
    }

Log in to reply
 

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