Friday, February 28, 2020

Meeting Rooms II

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.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

class Solution {
public:
    int minMeetingRooms(vector<vector<int>>& intervals) {
        int ans = 0;
        if (intervals.size() == 0) {
            return ans;
        }
        sort(intervals.begin(), intervals.end(), [](vector<int>& first,
                                                    vector<int>& second) {
            return first[0] < second[0];
        });

        priority_queue<int, vector<int>, greater<int>> pq;
        pq.push(intervals[0][1]);

        int counter = 1; 
        for (int i = 1; i < intervals.size(); i++) {
            while (!pq.empty() && pq.top() <= intervals[i][0]) {
                pq.pop();
                counter--;
            }
            counter++;
            ans = max(ans, counter);
            pq.push(intervals[i][1]);
        }
        return ans != 0 ? ans : 1;
    }
};

No comments:

Post a Comment