1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-10-18 14:52:09 +02:00

java: add «1942. The Number of the Smallest Unoccupied Chair»

URL:	https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-10-11 23:53:46 +02:00
parent 17817b1fe9
commit 260cae1010
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,35 @@
class Solution {
public int smallestChair(int[][] times, int targetFriend) {
int arrival = times[targetFriend][0];
Arrays.sort(times, (a, b) -> a[0] - b[0]);
int next = 0;
var leaving = new PriorityQueue<int[]>((a, b) -> a[0] - b[0]);
var available = new TreeSet<>();
for (var range : times) {
int arrived = range[0], left = range[1];
while (!leaving.isEmpty() && leaving.peek()[0] <= arrived) {
available.add(leaving.poll()[1]);
}
int current;
if (!available.isEmpty()) {
current = (int) available.first();
available.remove(current);
} else {
current = next++;
}
if (arrived == arrival) {
return current;
}
leaving.offer(new int[] {left, current});
}
// unreachable
return -1;
}
}