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:
parent
17817b1fe9
commit
260cae1010
1 changed files with 35 additions and 0 deletions
35
java/the-number-of-the-smallest-unoccupied-chair.java
Normal file
35
java/the-number-of-the-smallest-unoccupied-chair.java
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue