|
1 | 1 | package sorting; |
2 | 2 | // BEGIN STRIP |
| 3 | +import java.util.ArrayList; |
3 | 4 | import java.util.Arrays; |
| 5 | +import java.util.List; |
4 | 6 | import java.util.PriorityQueue; |
5 | 7 | // END STRIP |
6 | 8 |
|
@@ -52,36 +54,22 @@ public int minFacilitiesRequired(int[][] sessions) { |
52 | 54 | // TODO |
53 | 55 | // STUDENT return -1; |
54 | 56 | // BEGIN STRIP |
55 | | - |
56 | | - if (sessions.length == 0) { |
57 | | - return 0; |
| 57 | + // sweep line algorithm |
| 58 | + List<int[]> events = new ArrayList<>(); |
| 59 | + for (int[] session : sessions) { |
| 60 | + events.add(new int[]{session[0], 1}); |
| 61 | + events.add(new int[]{session[1], -1}); |
58 | 62 | } |
59 | | - // Sorting the sessions by the starting time. If they are the same compare the end time O(nlogn) |
60 | | - Arrays.sort(sessions, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); |
61 | | - |
62 | | - // Priority queue with end times of the sessions |
63 | | - PriorityQueue<Integer> queue = new PriorityQueue<>(); |
64 | | - queue.add(sessions[0][1]); |
65 | | - |
66 | | - // The idea is that for each new session, we check if we can use |
67 | | - // an existing facility or if we need an additional one of a session that was completed |
68 | | - // This is done lazily so at the end, the number of facilities in the queue is the final answer. |
69 | | - // Tnhis is node in O(n.log(n)) |
70 | | - for (int i = 1; i < sessions.length; i++) { |
71 | | - // check if we can use an existing session ? |
72 | | - if (queue.peek() <= sessions[i][0]) { |
73 | | - // using an existing facility means deleting it from the queue |
74 | | - // we delete the one finishing first (min priority queue) |
75 | | - queue.poll(); |
76 | | - } |
77 | | - queue.add(sessions[i][1]); // then we use a new facility |
| 63 | + events.sort((a, b) -> (a[0] == b[0]) ? a[1] - b[1] : a[0] - b[0]); |
| 64 | + int max = 0; |
| 65 | + int current = 0; |
| 66 | + for (int[] event : events |
| 67 | + ) { |
| 68 | + current += event[1]; |
| 69 | + max = Math.max(max, current); |
78 | 70 | } |
79 | | - return queue.size(); |
| 71 | + return max; |
80 | 72 | // END STRIP |
81 | 73 | } |
82 | 74 |
|
83 | | - |
84 | | - |
85 | | - |
86 | | - |
87 | 75 | } |
0 commit comments