1. 程式人生 > >253 Meeting Rooms II

253 Meeting Rooms II

imu ble 最大的 blog meet this return title oms

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), 
find the minimum number of conference rooms required. For example, Given [[
0, 30],[5, 10],[15, 20]], return 2.

看到區間求重疊的部分 , 就想到對區間排序(start, end?), 然後用堆模擬遍歷218 The Skyline Problem

Like the previous one Meeting Room, still need to sort the intervals using a comparator.

We need to simulate the process to know the maximum number of conference rooms needed.

We need to maintain a minimal heap, which sort the intervals according to their finishing time.

We add the interval to this heap one by one since they have already been sorted according to their start time.

So this heap acctually simulates the conference rooms, the number of elements it has instataneously is the number of rooms required.

Every time we add one interval to this heap, we need to check if its start time is greater than or equal to heap.peek(). If it is, that means there‘s some conferences in the heap which end now, and their rooms should be released.

/**
 * 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;
        Comparator<Interval> comp = new Comparator<Interval>() {
            public int compare(Interval i1, Interval i2) {
                return (i1.start==i2.start)? i1.end-i2.end : i1.start-i2.start;
            }
        };
        
        Arrays.sort(intervals, comp);
        PriorityQueue <Integer> que = new PriorityQueue<Integer>( new Comparator<Integer>(){  
            public int compare ( Integer int1, Integer int2 ){  
                return int1 - int2;  
            }  
        });  
        int rooms = 0;  
        for ( int i = 0; i < intervals.length; i ++ ){  
            while ( !que.isEmpty() && que.peek() <= intervals[ i ].start ){  
                que.poll();  
            }  
            que.offer ( intervals[ i ].end );
    rooms = Math.max ( rooms, que.size() );
        }
        return rooms; 
    }
}

  

  

這道題有follow up問求最多interval的時間點,返回任意一個就行。

隨便返回一個比如heap.size()最大的時候,heap.peek()

38行更新為

if(heap.size() > rooms)

  rooms = heap.size();

  maxMoment = heap.peak;

253 Meeting Rooms II