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

36 lines
829 B
Java
Raw Normal View History

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;
}
}