码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 855. Exam Room

时间:2018-11-20 14:58:47      阅读:410      评论:0      收藏:0      [点我收藏+]

标签:and   bsp   amr   sea   set   called   位置   roo   ber   

用set来做,seat() O(n),leave() O(logn)

注意一些边界情况和下标即可,最容易遗漏的就是最左边和最右边的位置。

class ExamRoom {
public:
    ExamRoom(int N):n(N){};
    
    int seat() {
        if (s.size()==0){ s.insert(0); return 0;}
        int res=0;
        int max_dis=*s.begin();
        int prev=-1;
        
        for (int x:s){
            if (prev!=-1){
                int cur_dis = (x-prev)/2;
                if (cur_dis>max_dis){
                    max_dis = cur_dis;
                    res = prev+cur_dis;
                }
            }
            prev = x;
        }
        if (n-1-prev>max_dis){
            max_dis = n-1-prev;
            res = n-1;
        }
        s.insert(res);
        return res;
    }
    
    void leave(int p) {
        s.erase(p);
    }
    
private:
    int n;          // number of seats
    set<int> s;     // set records the seated seats
};

/**
 * Your ExamRoom object will be instantiated and called as such:
 * ExamRoom obj = new ExamRoom(N);
 * int param_1 = obj.seat();
 * obj.leave(p);
 */

 

LeetCode 855. Exam Room

标签:and   bsp   amr   sea   set   called   位置   roo   ber   

原文地址:https://www.cnblogs.com/hankunyan/p/9988352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!