Share my Java Solution using PriorityQueue


  • 0
    /**
     * Definition for an interval.
     * public class Interval {
     *     int start;
     *     int end;
     *     Interval() { start = 0; end = 0; }
     *     Interval(int s, int e) { start = s; end = e; }
     * }
     */
    public class Solution {
        public int minMeetingRooms(Interval[] intervals) {
            if (intervals == null || intervals.length == 0) {
                return 0;
            }
            Arrays.sort(intervals, new Comparator<Interval>(){
                public int compare(Interval a, Interval b) {
                    if (a.start == b.start) {
                        return a.end - b.end;
                    }
                    return a.start - b.start;
                }
            });
            PriorityQueue<Interval> heap = new PriorityQueue<Interval>(new Comparator<Interval>(){
                public int compare(Interval a, Interval b) {
                    if (a.end == b.end) {
                        return a.start - b.start;
                    }
                    return a.end - b.end;
                }
            });
            for (Interval i : intervals) {
                if (!heap.isEmpty()) {
                    if (i.start >= heap.peek().end) {
                        heap.poll();
                    }
                }
                heap.add(i);
            }
            return heap.size();
        }
    }
    

Log in to reply
 

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