855. Exam Room

195 篇文章 0 订阅
Description

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§ 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 <= N <= 10^9
ExamRoom.seat() and ExamRoom.leave() will be called at most 10^4 times across all test cases.
Calls to ExamRoom.leave§ are guaranteed to have a student currently sitting in seat number p.

Problem URL


Solution

构建一个Exam room类,传入一行的座位数N,每次通过调用seat()的方法可以安排一个考生坐下,要保证考生之间的距离均匀且最大,如果距离相同则尽量靠左安排,也就是说第一个考生坐在0,第二个坐在N - 1。

leave()方法保证传入一个有人坐的座位,将它删除。

We construct an interval class, which denotes the free space between two student. x is left one, y is right one, dist is the mid distance between two student, that is the new seat position. There are two special case, if x == -1, dist = y; y == N, dist = N - 1 - x. Because we add two boundary on both side, so it means left or right is empty and ready for next seat.

In constructor, initialize a priority queue which poll max dist first and if dist is equal, poll left seat first. push an initial boundary interval [-1, N] in it.

In seat(), we poll out interval, if interval.x = -1, seat there, elif y = N, seat there; Or we should calculate the mid position and push two new interavals in pq.

In leave, convert pq to a list then iteratively find two intervals. One starts at p and one end at p. Remove these two intervals, and then push a new interval which covers them in pq.

Code
class ExamRoom {
    private PriorityQueue<Interval> pq;
    private int N;
    
    class Interval{
        int x;
        int y;
        int dist;
        public Interval(int x, int y){
            this.x = x;
            this.y = y;
            if (x == -1){
                this.dist = y;
            }
            else if (y == N){
                this.dist = N - 1 - x;
            }
            else{
                this.dist = Math.abs(y - x) / 2;
            }
        }
    }
    public ExamRoom(int N) {
        this.pq = new PriorityQueue<Interval>((a, b) -> a.dist != b.dist ? b.dist - a.dist : a.x - b.x);
        this.N = N;
        pq.add(new Interval(-1, N));
    }
    
    public int seat() {
        int seat = 0;
        Interval in = pq.poll();
        if (in.x == -1){
            seat = 0;
        }
        else if(in.y == N){
            seat = N - 1;
        }
        else{
            seat = (in.x + in.y) / 2;
        }
        pq.offer(new Interval(in.x, seat));
        pq.offer(new Interval(seat, in.y));
        
        return seat;
    }
    
    public void leave(int p) {
        Interval head = null, tail = null;
        List<Interval> list = new ArrayList<>(pq);
        for (Interval in : list){
            if (in.x == p){
                tail = in;
            }
            if (in.y == p){
                head = in;
            }
            if (head != null && tail != null){
                break;
            }
        }
        pq.remove(head);
        pq.remove(tail);
        pq.offer(new Interval(head.x, tail.y));
    }
}

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

Time Complexity: O(nlogN)
Space Complexity: O(N)


Review
以下是一个简单的考场安排系统的Idea代码: ```python # 假设已经有所有考生和考场信息的数据 # 考场信息包括考场编号、考场容量、座位号等 class ExamRoom: def __init__(self, room_id, capacity, seats): self.room_id = room_id self.capacity = capacity self.seats = seats # 考生信息包括姓名、准考证号、所在考场等 class Examinee: def __init__(self, name, exam_id, room_id, seat_id): self.name = name self.exam_id = exam_id self.room_id = room_id self.seat_id = seat_id # 考场安排系统类 class ExamArrangementSystem: def __init__(self): self.exam_rooms = [] # 所有考场信息 self.examinees = [] # 所有考生信息 # 添加考场信息 def add_exam_room(self, room_id, capacity, seats): exam_room = ExamRoom(room_id, capacity, seats) self.exam_rooms.append(exam_room) # 添加考生信息 def add_examinee(self, name, exam_id, room_id, seat_id): examinee = Examinee(name, exam_id, room_id, seat_id) self.examinees.append(examinee) # 根据考生准考证号查询考生信息 def search_examinee_by_exam_id(self, exam_id): for examinee in self.examinees: if examinee.exam_id == exam_id: return examinee return None # 根据考场编号查询考场信息 def search_exam_room_by_room_id(self, room_id): for exam_room in self.exam_rooms: if exam_room.room_id == room_id: return exam_room return None # 根据考场编号和座位号查询座位是否空闲 def is_seat_available(self, room_id, seat_id): exam_room = self.search_exam_room_by_room_id(room_id) if exam_room is not None: if exam_room.seats[seat_id-1] is None: return True return False # 安排考生座位 def arrange_seat(self, exam_id, room_id, seat_id): examinee = self.search_examinee_by_exam_id(exam_id) if examinee is not None: exam_room = self.search_exam_room_by_room_id(room_id) if exam_room is not None: if self.is_seat_available(room_id, seat_id): exam_room.seats[seat_id-1] = examinee examinee.room_id = room_id examinee.seat_id = seat_id print(f"{examinee.name}({examinee.exam_id})已安排在{room_id}考场{seat_id}座位") else: print("该座位已被占用,请重新选择座位") else: print("该考场不存在,请重新输入考场编号") else: print("该考生不存在,请重新输入准考证号") # 使用示例 exam_arrangement = ExamArrangementSystem() # 添加考场信息 exam_arrangement.add_exam_room("A101", 50, [None]*50) exam_arrangement.add_exam_room("A102", 80, [None]*80) # 添加考生信息 exam_arrangement.add_examinee("张三", "2022010101", None, None) exam_arrangement.add_examinee("李四", "2022010102", None, None) # 安排考生座位 exam_arrangement.arrange_seat("2022010101", "A101", 10) exam_arrangement.arrange_seat("2022010102", "A102", 20) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值