[LeetCode] Seat Reservation Manager

1845. Seat Reservation Manager

Design a system that manages the reservation state of n seats that are numbered from 1 to n.

Implement the SeatManager class:

  • SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available.
  • int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.
  • void unreserve(int seatNumber) Unreserves the seat with the given seatNumber.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class SeatManager {
priority_queue<int, vector<int>, greater<int>> pq;
int seat = 1;
public:
SeatManager(int n) {

}

int reserve() {
if(pq.empty()) {
return seat++;
} else {
auto s = pq.top(); pq.pop();
return s;
}
}

void unreserve(int seatNumber) {
if(seatNumber + 1 == seat) {
seat--;
} else {
pq.push(seatNumber);
}
}
};

/**
* Your SeatManager object will be instantiated and called as such:
* SeatManager* obj = new SeatManager(n);
* int param_1 = obj->reserve();
* obj->unreserve(seatNumber);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/06/PS/LeetCode/seat-reservation-manager/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.