855. Exam Room

In an exam room, there areNseats in a single row, numbered0, 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 classExamRoom(int N) that exposes two functions:ExamRoom.seat() returning anint representing what seat the student sat in, andExamRoom.leave(int p) representing that the student in seat numberp now leaves the room. It is guaranteed that any calls toExamRoom.leave(p)have a student sitting in seatp.

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 {

    int N;
    TreeSet<Integer> students;

    public ExamRoom(int N) {
        this.N = N;
        students = new TreeSet<>();
    }

    public int seat() {

        int student = 0;
        if (students.size() > 0){
            int dist = students.first();
            Integer prev = null;

            for (int s : students){
                if (prev != null){
                    int d = (s - prev) / 2;
                    if (d > dist){
                        dist = d;
                        student = prev + d;
                    }
                    prev = s;
                }
                else{
                    prev = s;
                }
            }

            if (N - 1 - students.last() > dist)
                student = N - 1;
        }

        students.add(student);
        return student;
    }

    public void leave(int p) {
        students.remove(p);
    }
}

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

results for ""

    No results matching ""