LeetCode – Meeting Rooms II (Java)

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] find the minimum number of conference rooms required.

Java Solution

public int minMeetingRooms(Interval[] intervals) {
    if(intervals==null||intervals.length==0)
        return 0;
 
    Arrays.sort(intervals, new Comparator<Interval>(){
        public int compare(Interval i1, Interval i2){
            return i1.start-i2.start;
        }
    });
 
    PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
    int count=1;
    queue.offer(intervals[0].end);
 
    for(int i=1; i<intervals.length; i++){
        if(intervals[i].start<queue.peek()){
            count++;
 
        }else{
            queue.poll();
        }
 
        queue.offer(intervals[i].end);
    }
 
    return count;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Ankur

    Instead of Priority Queue take simple queue to store elements but just sort by endTime .


    private static int minMeetingRoomsQueue(Interval[] inte) {
    int c = 0;
    Arrays.sort(inte,new Comparator(){

    @Override
    public int compare(Interval o1, Interval o2) {
    return o1.eTime - o2.eTime;
    }

    });
    Queue q = new LinkedList();
    q.add(inte[0].eTime);
    c++;
    for(int i=1;i<inte.length;i++){
    if(inte[i].sTime < q.peek()){
    c++;
    }else{
    q.poll();
    }
    q.add(inte[i].eTime);
    }
    return c;
    }