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.

思路:这题就是扫描每个区间,需要注意的地方是:第一个区间和最后一个区间,因为如果大,那么只能坐第一个和最后一个位子。尽可能的间隔开来,所以这两个区间要分别对待。算法就是:算每个区间是否是最大,然后判断是第一个还是中间的,还是最后的,如果是中间的,要加入相应的index,值就是左边和右边的和 除以2,如果最大区间是第一个,那么坐第一个位子,如果是最后,那么直接坐最后一个位子;Seat O(N), Leave O(N)

class ExamRoom {
    private List<Integer> list;
    private int n;
    public ExamRoom(int n) {
        this.n = n;
        this.list = new ArrayList<Integer>();
    }
    
    public int seat() {
        int maxdis = 0;
        if(list.isEmpty()) {
            list.add(0);
            return 0;
        }
        
        // 算最前面,和最后面的距离;
        maxdis = Math.max(list.get(0) - 0, n - 1 - list.get(list.size() - 1));
        for(int i = 0; i < list.size() - 1; i++) {
            maxdis = Math.max(maxdis, (list.get(i + 1) - list.get(i)) / 2);
        }
        
        if(maxdis == list.get(0)) {
            list.add(0, 0);
            return 0;
        }
        
        for(int i = 0; i < list.size() - 1; i++) {
            if(maxdis == (list.get(i + 1) - list.get(i)) / 2) {
                list.add(i + 1, (list.get(i + 1) + list.get(i)) / 2);   
                return list.get(i + 1);
            }
        }
        
        list.add(n - 1);
        return n - 1;
    }
    
    public void leave(int p) {
        for(int i = 0; i < list.size(); i++) {
            if(list.get(i) == p) {
                list.remove(i);
            }
        }
    }
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值