253. 会议室 II
给你一个会议时间安排的数组 intervals ,每个会议时间都会包括开始和结束的时间 intervals[i] = [starti, endi] ,返回 所需会议室的最小数量 。
示例 1:
输入: intervals = [[0,30],[5,10],[15,20]]
输出: 2
示例 2:
输入: intervals = [[7,10],[2,4]]
输出: 1
提示:
1 <= intervals.length <= 1040 <= starti < endi <= 106
var minMeetingRooms = function(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const heap = new Heap((a, b) => a < b);
let result = 0;
for (let i = 0; i < intervals.length; i++) {
const [start, end] = intervals[i];
if ((!result && !heap.getSize()) || (heap.getSize() && start < heap.getTop())) {
result++;
}
if (heap.getSize() && heap.getTop() <= start) {
heap.pop();
}
heap.push(end);
}
return result;
}
class Heap {
constructor(compare) {
this.nodeList = [];
this.compare = typeof compare === 'function' ? compare : this.defaultCompare;
}
defaultCompare(a, b) {
return a > b;
}
getSize() {
return this.nodeList.length;
}
getTop() {
return this.nodeList[0];
}
push(value) {
this.nodeList.push(value);
this.up(this.nodeList.length - 1);
}
// 父结点的index值
parent(index) {
return index % 2 === 0 ? index / 2 - 1 : (index - 1) / 2;
}
up(index) {
const { nodeList, compare, parent } = this;
while (index > 0 && compare(nodeList[index], nodeList[parent(index)])) {
const temp = nodeList[index];
nodeList[index] = nodeList[parent(index)];
nodeList[parent(index)] = temp;
index = parent(index);
}
}
pop() {
if (this.nodeList.length === 0) {
return null;
}
const top = this.nodeList[0];
this.nodeList[0] = this.nodeList[this.nodeList.length - 1];
this.nodeList.pop();
if (this.nodeList.length > 1) {
this.down(0);
}
return top;
}
left(index) {
return index * 2 + 1;
}
right(index) {
return index * 2 + 2;
}
down(index) {
const { nodeList, left, right, compare } = this;
while (left(index) < nodeList.length) {
let target = left(index);
if (right(index) < nodeList.length && compare(nodeList[right(index)], nodeList[left(index)])) {
target = right(index);
}
if (compare(nodeList[index], nodeList[target])) {
return;
}
const temp = nodeList[index];
nodeList[index] = nodeList[target];
nodeList[target] = temp;
index = target;
}
}
}