zoukankan      html  css  js  c++  java
  • 253. 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

    解题思路:

    要最少的最多的房间,我们只要满足时段内重复最多的不同会议就好。

    可以将会议开始和结束都存到最小堆里,用pair存储,第二个值用于标识是开始还是结束。

    我从最小堆中取出堆顶元素(即最小值)

    若其为起点,则rooms自增一;若其为重点,首先将当前rooms的值与ret相比,取最大的那个,然后rooms自减一。

    还有一个很神奇的解法

    代码:

    用最小堆来解:

    /**
     * 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) {
            priority_queue<pair<int,int>, vector<pair<int,int>>, greater<> > q;
            int ret = 0;
            for(Interval i : intervals){
                q.push({i.start, 1}); //represent start
                q.push({i.end, -1}); //represent end
            }
            
            int rooms = 0;
            while(!q.empty()){
                auto p = q.top();
                q.pop();
                if(p.second == 1){
                    //represent start
                    rooms++;
                }else{
                    //represent end
                    ret = max(ret, rooms);
                    rooms--;
                }
            }
            
            
            return ret;
        }
    };

    很神奇的解法:

    /**
     * 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) {
            vector<int> starts, ends;
            int res = 0, endpos = 0;
            for (auto a : intervals) {
                starts.push_back(a.start);
                ends.push_back(a.end);
            }
            sort(starts.begin(), starts.end());
            sort(ends.begin(), ends.end());
            for (int i = 0; i < intervals.size(); ++i) {
                if (starts[i] < ends[endpos]) ++res;
                else ++endpos;
            }
            return res;
        }
    };
  • 相关阅读:
    C#使用R.net(RDotNet)混合编程,配置环境时发生错误“This 32-bit process failed to load the library R.dll. Native error message is '句柄无效。'””
    Error in shinyAppDir(x) : No Shiny application exists at the path "~/app"处理方法
    vm拷贝cloudera-scm-agent造成问题
    cloudera目录位置
    centos下安装cdh5
    elasticsearch常用的插件
    elasticsearch 安装
    mongod的主要参数有
    mongodb.conf配置文件详解
    centos 安装 mongo3.0
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9194294.html
Copyright © 2011-2022 走看看