253. Meeting Rooms II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BigFatSheep/article/details/82980492

问题描述

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

题目链接:

思路分析

给一个存储了会议开始时间和结束时间的数组,问这些会议至少需要几个会议室才能正常召开。

We use a map to store the number of meeting rooms needed. First iteration of vector intervals stores number of meeting rooms needed in a specific time. When a meeting starts, the map’s value add one. When a meeting ends, the map’s value minus one.

Then in the second iteration, we iterate the map, the initial value of rooms is zero. In a specific time point, just simply add the map’s value. If at that time one or multiple new meetings start, rooms number would add the same number. Then comparing this value with the max rooms number, we could get the final result.

代码

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    int minMeetingRooms(vector<Interval>& intervals) {
        map<int, int> roomChanges;
        for (auto i : intervals){
            roomChanges[i.start] += 1;
            roomChanges[i.end] -= 1;
        }
        int rooms = 0, maxRoom = 0;
        for (auto change : roomChanges){
            rooms += change.second;
            maxRoom = max(maxRoom, rooms);
        }
        return maxRoom;
    }
};

时间复杂度:O(n)
空间复杂度:O(n)


反思

很巧妙的把握住了整体的思想,不计较每次的变化。

猜你喜欢

转载自blog.csdn.net/BigFatSheep/article/details/82980492
今日推荐