From 260cae1010ebe967076f95ab36ca2b8de941565a Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 11 Oct 2024 23:53:46 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB1942.=20The=20Number=20of?= =?UTF-8?q?=20the=20Smallest=20Unoccupied=20Chair=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair/ Signed-off-by: Matej Focko --- ...mber-of-the-smallest-unoccupied-chair.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 java/the-number-of-the-smallest-unoccupied-chair.java diff --git a/java/the-number-of-the-smallest-unoccupied-chair.java b/java/the-number-of-the-smallest-unoccupied-chair.java new file mode 100644 index 0000000..58d0d97 --- /dev/null +++ b/java/the-number-of-the-smallest-unoccupied-chair.java @@ -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((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; + } +}