| 1 | |
| 2 | class Solution { |
| 3 | public int smallestChair(int[][] times, int targetFriend) { |
| 4 | int targetArrival = times[targetFriend][0]; //[a,d] |
| 5 | Arrays.sort(times, new Comparator<int[]>(){ |
| 6 | public int compare(int a[], int b[]){ |
| 7 | return a[0] - b[0]; |
| 8 | } |
| 9 | }); |
| 10 | //[lt,chairNo] |
| 11 | PriorityQueue<int[]> occupied = new PriorityQueue<>(new Comparator<int[]>(){ |
| 12 | public int compare(int a[], int b[]){ |
| 13 | return a[0] - b[0]; |
| 14 | } |
| 15 | }); |
| 16 | PriorityQueue<Integer> available = new PriorityQueue<>(); |
| 17 | int chairNo=0; |
| 18 | for(int time[] : times){ |
| 19 | int arrTime = time[0]; |
| 20 | int leavingTime = time[1]; |
| 21 | while(!occupied.isEmpty() && occupied.peek()[0] <= arrTime){ |
| 22 | available.offer(occupied.poll()[1]); |
| 23 | } |
| 24 | int currentChairNo; |
| 25 | if(available.isEmpty()){ |
| 26 | currentChairNo = chairNo; |
| 27 | chairNo++; |
| 28 | }else{ |
| 29 | currentChairNo = available.poll(); |
| 30 | } |
| 31 | if(targetArrival == arrTime) return currentChairNo; |
| 32 | occupied.offer(new int[]{leavingTime, currentChairNo}); |
| 33 | } |
| 34 | return -1; |
| 35 | } |
| 36 | } |