[LeetCode] 会议室问题(Meeting Rooms)

By Long Luo

252. 会议室 253. 会议室 II
2402. 会议室 III

252. 会议室

暴力

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static boolean canAttendMeetings_bf(int[][] intervals) {
int len = intervals.length;
if (len <= 1) {
return true;
}

for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
int[] m1 = intervals[i];
int[] m2 = intervals[j];

if (!(m1[1] <= m2[0] || m1[0] >= m2[1])) {
return false;
}
}
}

return true;
}

排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static boolean canAttendMeetings(int[][] intervals) {
if (intervals == null || intervals.length <= 1) {
return true;
}

Arrays.sort(intervals, (a, b) -> {
if (a[0] == b[0]) {
return a[1] - b[1];
}
return a[0] - b[0];
});

for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}

return true;
}

253. 会议室 II

253. 会议室 II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public int minMeetingRooms(int[][] intervals) {
if (intervals == null || intervals.length <= 1) {
return intervals.length;
}

int len = intervals.length;

Arrays.sort(intervals, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);

PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
return a[1] == b[1] ? a[0] - b[0] : a[1] - b[1];
}
});

int min = 1;

pq.offer(intervals[0]);

for (int i = 1; i < len; i++) {
int start = intervals[i][0];
int end = intervals[i][1];

if (!pq.isEmpty() && start < pq.peek()[1]) {
pq.offer(intervals[i]);
min = Math.max(min, pq.size());
} else {
pq.poll();
pq.offer(intervals[i]);
}
}

return min;
}

2402. 会议室 III

todo

参考文献

  1. 会议室 II
  2. 图解转化为上下车问题 O(nlogn)

All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗