【发布时间】:2022-01-17 05:33:43
【问题描述】:
我正在使用 PriorityQueue 来解决 Leetcode 中的会议室 II 问题。我开发了自己的解决方案,但在某些测试用例上失败了,但在我看来,它与提供的解决方案没有区别,但该解决方案通过了所有测试。两者有什么区别?我看到的主要区别是传递给 minHeap 的比较器,但我的理解是默认情况下,PriorityQueue 会将最小的数字保留在头部。
给定解决方案:
public int minMeetingRooms(int[][] intervals) {
// Check for the base case. If there are no intervals, return 0
if (intervals.length == 0) {
return 0;
}
// Min heap
PriorityQueue<Integer> allocator =
new PriorityQueue<Integer>(
intervals.length,
new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return a - b;
}
});
// Sort the intervals by start time
Arrays.sort(
intervals,
new Comparator<int[]>() {
public int compare(final int[] a, final int[] b) {
return a[0] - b[0];
}
});
// Add the first meeting
allocator.add(intervals[0][1]);
// Iterate over remaining intervals
for (int i = 1; i < intervals.length; i++) {
// If the room due to free up the earliest is free, assign that room to this meeting.
if (intervals[i][0] >= allocator.peek()) {
allocator.poll();
}
// If a new room is to be assigned, then also we add to the heap,
// If an old room is allocated, then also we have to add to the heap with updated end time.
allocator.add(intervals[i][1]);
}
// The size of the heap tells us the minimum rooms required for all the meetings.
return allocator.size();
}
}
我的实现:
public int minMeetingRooms(int[][] intervals) {
if (intervals.length == 0) {
return 0;
}
Comparator<int[]> comp = new Comparator<int[]>(){
public int compare(int[] A, int[] B){
if(A[0]<B[0]){
return -1;
}
else if(A[0]>B[0]){
return 0;
}
else{
return 1;
}
}
};
Arrays.sort(intervals, comp);
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
minHeap.add(intervals[0][1]);
for(int i = 1; i<intervals.length; i++){
if(intervals[i][0] >= minHeap.peek()){
minHeap.poll();
}
minHeap.add(intervals[i][1]);
}
return minHeap.size();
}
}
【问题讨论】:
标签: java java-8 comparator priority-queue min-heap