Meeting Rooms II解题报告

Description:

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:

For example,
Given [[0, 30],[5, 10],[15, 20]],
return 2.

Link:

https://leetcode.com/problems/meeting-rooms-ii/description/

解题方法:

先记录每个interval开始和结束所需要的房间数,当开始时,需要的房间数为1,而结束时,需要的房间数为-1;
再遍历一遍以上记录的数组,这样所需的房间数会随着以上的记录不断的变化,用一个变量去记录随时变化的房间数出现的最大值就是我们所求的值。

Tips:

用map作为储存结构,就会按照时间的先后来储存每个时间点需要的房间数。

Time Complexity:

因为map的遍历并不是O(N),所以时间为O(NlogN)。

完整代码:

int minMeetingRooms(vector& intervals) 
    {
        map hash;
        for(auto a: intervals)
        {
            hash[a.start]++;
            hash[a.end]--;
        }
        int currRoom = 0, maxRoom = 0;
        for(auto a: hash)
        {
            currRoom += a.second;
            maxRoom = currRoom > maxRoom ? currRoom : maxRoom;
        }
        return maxRoom;
    }

你可能感兴趣的:(Meeting Rooms II解题报告)