Skip to content

Commit dcedd9f

Browse files
refactor 253
1 parent 9d97457 commit dcedd9f

File tree

1 file changed

+27
-32
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+27
-32
lines changed

src/main/java/com/fishercoder/solutions/_253.java

Lines changed: 27 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,47 +5,42 @@
55
import java.util.Arrays;
66
import java.util.PriorityQueue;
77

8-
/**
9-
* Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei),
10-
* find the minimum number of conference rooms required.
11-
12-
For example,
13-
Given [[0, 30],[5, 10],[15, 20]],
14-
return 2.
15-
*/
168
public class _253 {
9+
public static class Solution1 {
1710

18-
public int minMeetingRooms(Interval[] intervals) {
19-
if (intervals == null || intervals.length == 0) {
20-
return 0;
21-
}
11+
public int minMeetingRooms(Interval[] intervals) {
12+
if (intervals == null || intervals.length == 0) {
13+
return 0;
14+
}
15+
16+
// Sort the intervals by start time
17+
Arrays.sort(intervals, (a, b) -> a.start - b.start);
2218

23-
// Sort the intervals by start time
24-
Arrays.sort(intervals, (a, b) -> a.start - b.start);
19+
// Use a min heap to track the minimum end time of merged intervals
20+
PriorityQueue<Interval> heap = new PriorityQueue<>(intervals.length, (a, b) -> a.end - b.end);
2521

26-
// Use a min heap to track the minimum end time of merged intervals
27-
PriorityQueue<Interval> heap = new PriorityQueue<>(intervals.length, (a, b) -> a.end - b.end);
22+
// start with the first meeting, put it to a meeting room
23+
heap.offer(intervals[0]);
2824

29-
// start with the first meeting, put it to a meeting room
30-
heap.offer(intervals[0]);
25+
for (int i = 1; i < intervals.length; i++) {
26+
// get the meeting room that finishes earliest
27+
Interval interval = heap.poll();
3128

32-
for (int i = 1; i < intervals.length; i++) {
33-
// get the meeting room that finishes earliest
34-
Interval interval = heap.poll();
29+
if (intervals[i].start >= interval.end) {
30+
// if the current meeting starts right after
31+
// there's no need for a new room, merge the interval
32+
interval.end = intervals[i].end;
33+
} else {
34+
// otherwise, this meeting needs a new room
35+
heap.offer(intervals[i]);
36+
}
3537

36-
if (intervals[i].start >= interval.end) {
37-
// if the current meeting starts right after
38-
// there's no need for a new room, merge the interval
39-
interval.end = intervals[i].end;
40-
} else {
41-
// otherwise, this meeting needs a new room
42-
heap.offer(intervals[i]);
38+
// don't forget to put the meeting room back
39+
heap.offer(interval);
4340
}
4441

45-
// don't forget to put the meeting room back
46-
heap.offer(interval);
42+
return heap.size();
4743
}
48-
49-
return heap.size();
5044
}
5145
}
46+

0 commit comments

Comments
 (0)