LeetCode #855. Exam Room

题目描述:

In an exam room, there are N seats in a single row, numbered 0, 1, 2, ..., N-1.

When a student enters the room, they must sit in the seat that maximizes the distance to the closest person.  If there are multiple such seats, they sit in the seat with the lowest number.  (Also, if no one is in the room, then the student sits at seat number 0.)

Return a class ExamRoom(int N) that exposes two functions: ExamRoom.seat() returning an int representing what seat the student sat in, and ExamRoom.leave(int p) representing that the student in seat number p now leaves the room.  It is guaranteed that any calls to ExamRoom.leave(p) have a student sitting in seat p.

Example 1:

Input: ["ExamRoom","seat","seat","seat","seat","leave","seat"], [[10],[],[],[],[],[4],[]]
Output: [null,0,9,4,2,null,5]
Explanation:
ExamRoom(10) -> null
seat() -> 0, no one is in the room, then the student sits at seat number 0.
seat() -> 9, the student sits at the last seat number 9.
seat() -> 4, the student sits at the last seat number 4.
seat() -> 2, the student sits at the last seat number 2.
leave(4) -> null
seat() -> 5, the student sits at the last seat number 5.
​​​​​Note:
  1. 1 <= N <= 10^9
  2. ExamRoom.seat() and ExamRoom.leave() will be called at most 10^4 times across all test cases.
  3. Calls to ExamRoom.leave(p) are guaranteed to have a student currently sitting in seat number p.
class ExamRoom {
public:
    ExamRoom(int N) {
        n=N;
    }
    
    int seat() {
        if(s.empty())
        {
            s.insert(0);
            return 0;
        }
        bool first=s.count(0);
        bool last=s.count(n-1);
        int pre=0, result=0, max_dist=0;
        // 遍历set时,需要单独考虑两个端点,当它们没有占用时可以考虑
        // 而且计算两个端点到其他点的距离时不需要除二
        for(const int& i:s)
        {
            int dist=(pre==0&&!first)?i-pre:(i-pre)/2;
            if(dist>max_dist)
            {
                max_dist=dist;
                if(pre==0&&!first) result=0;
                else result=(i+pre)/2;
            }
            pre=i;
        }
        if(n-1-pre>max_dist&&!last) result=n-1;
        s.insert(result);
        return result;
    }
    
    void leave(int p) {
        s.erase(p);
    }

private:
    int n;
    set<int> s;
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值