LeetCode 855. Exam Room

Posted 約束の空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 855. Exam Room相关的知识,希望对你有一定的参考价值。

用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的主要内容,如果未能解决你的问题,请参考以下文章

855. Exam Room

855. Exam Room

Leetcode: Robot Room Cleaner

leetcode489 - Robot Room Cleaner - hard

[LeetCode] 489. Robot Room Cleaner 扫地机器人

Leetcode 问题 489. Robot Room Cleaner - 为啥我的解决方案不起作用