Saturday, November 12, 2016

Meeting Room II -- LeetCode

[Question]
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.
[Analysis]
This is another interval related problem. First, we can sort all the starts (s1, s2, ...) and ends (e1, e2, ...) into two series. Then, for each ends 'e', count how many starts are before 'e' -- that is how many rooms we need before time 'e'. Time complexity is O(N Log N), space complexity is O(N).

The similar problems: "Non-overlapping Intervals", "Minimum Number of Arrows to Burst Balloons".

[Solution]
public class Solution {
    public int minMeetingRooms(vector<Interval> intervals) {
        vector<int> starts(intervals.size(), 0);
        vector<int> ends(intervals.size(), 0);
        for (int i=0; i<intervals.size(); i++) {
            starts[i] = intervals[i].start;
            ends[i] = intervals[i].end;
        }
        sort (starts.begin(), starts.end());
        sort(ends.begin(), ends.end());
        int room=0; int j=0;
        int res =0;
        for (auto e: ends) {
            while (starts[j]<e) {
                j++; room++;
                res = max(res, room);
            }
            room--;
         }
         return res;
    }
}

//
// Using Hash Table
//
class Solution {
public:
    int minMeetingRooms(vector<Interval>& intervals) {
        map<int, int> m;
        for (auto a : intervals) {
            m[a.start]++;
            m[a.end]--;
        }
        int rooms = 0, res = 0;
        for (auto it : m) {
            res = max(res, rooms += it.second);
        }
        return res;
    }
};

No comments:

Post a Comment