568. Seat Desk
A ticket desk manages n numbered seats, 1 through n, and every seat starts out free. Implement the class SeatDesk:
SeatDesk(int n)creates the desk with seats1..nall free.int reserve()reserves the free seat with the smallest number and returns that number.void unreserve(int seat)makes a previously reserved seat free again, so it can be handed out later.
Calls are always valid: reserve is only called when at least one seat is free, and unreserve is only called with a seat that is currently reserved. Each operation should run in O(log n) time or better, with O(n) total space.
Example 1
- Input:
- operations = ["SeatDesk","reserve","reserve","reserve","unreserve","reserve"]arguments = [[4],[],[],[],[2],[]]
- Output:
- [null,1,2,3,null,2]
- Explanation:
Seats 1, 2, 3 are handed out; after seat 2 is released, the next reserve returns 2 again, the smallest free seat.
Example 2
- Input:
- operations = ["SeatDesk","reserve","unreserve","reserve"]arguments = [[1],[],[1],[]]
- Output:
- [null,1,null,1]
- Explanation:
With a single seat, releasing it makes it available again.
Example 3
- Input:
- operations = ["SeatDesk","reserve","reserve","unreserve","unreserve","reserve","reserve","reserve"]arguments = [[3],[],[],[2],[1],[],[],[]]
- Output:
- [null,1,2,null,null,1,2,3]
- Explanation:
Seats 2 then 1 are released, but reserve always returns the smallest free one first: 1, 2, then the untouched seat 3.
Constraints
1 ≤ n ≤ 100000- At most
100000calls in total toreserveandunreserve. 1 ≤ seat ≤ n, and the seat is currently reserved.reserveis only called while a free seat exists.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Input
- Each case is an operation log.
operationsnames the class first and then each method call;argumentsholds the arguments for each, in the same order. Your answer is one list with a result per operation -nullfor the constructor and for methods that return nothing.
Expected complexity
- Time
- O(log n) per operation
- Space
- O(n)