zoukankan      html  css  js  c++  java
  • [Locked] Meeting Room I && II

    Meeting Room

    Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.

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

    分析:

      即判断这些区间是否有重叠,遍历一遍,前一个区间的右边界不大于后一个区间的左边界即可,时间复杂度O(n),空间复杂度O(1)

    代码:

    bool canAttendAll(vector<vector<int> > time) {
        for(int i = 1; i < time.size(); i++)
            if(time[i][0] < time[i - 1][1])
                return false;
        return true;
    }

    Meeting Room 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.

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

    分析:

      典型贪心法问题,尝试3种方案:1、开始时间优先,可行;2、结束时间优先,可以找到反例,[2,5][4,6][6,10][5,12],2个房间即可,可用该解法得要3个房间,故否决;3、持续时间优先,可以找到反例,[4,5][4,6][6,10][5,12],2个房间即可,可用该解法需要3个房间,故否决;

    解法: 

      开始时间优先

    证明:

      有[x1, y1],[x2, y2],x1 < x2,y1 > x2,得开两个房间;对于[x3, y3],[x4, y4],必有x4 >= x3 >= x2。那么,若x3 >= y1,将[x3, y3]归入[x1, y1]房间中,则如果x4 < y2,那么x3 < y2,若交换[x3, y3]和[x4, y4]的顺序,还是必然还得多开一个房间,结果无差别;若x4 >= y2,可以将 [x4, y4]归入[x2, y2]房间中,交换[x3, y3]和[x4, y4]的顺序,结果并不会更好,反而可能更差。故开始时间优先的方法是最优的。

    代码:

    bool cmp(vector<int> &a, vector<int> &b) {
        return a[0] < b[0];
    }
    int roomCount(vector<vector<int> > time) {
        if(time.empty())
            return 0;
        sort(time.begin(), time.end(), cmp);
        vector<int> room(1, INT_MIN);
        int count = 1;
        for(auto t : time) {
            bool openNew = true;
            for(int &r : room) {
                if(r <= t[0]) {
                    r = t[1];
                    openNew = false;
                    break;
                }
            }
            if(openNew) {
                count++;
                room.push_back(t[1]);
            }
        }
        return count;
    }

      

  • 相关阅读:
    对于线程同步的浅薄理解
    线程安全之ConcurrentQueue<T>队列
    关于mybatis拦截器,对结果集进行拦截
    oracle 分析函数
    C# ikvm 运行htmlunit Provider com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl not found
    IronJs 无相关源?
    js div 内容显示分页
    JavascriptTAB切换 AND JqueryTAB切换
    php中mysql数据库操作类 -李盛鹏 -博客园
    sublime text 之snippet功能的使用 -李盛鹏 -博客园
  • 原文地址:https://www.cnblogs.com/littletail/p/5208026.html
Copyright © 2011-2022 走看看