LeetCode/java/the-number-of-the-smallest-unoccupied-chair.java

36 lines
829 B
Java
Raw Permalink 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;
}
}