|
| 1 | +/** |
| 2 | + * 2335. 装满杯子需要的最短总时长 |
| 3 | + * @param {number[]} amount |
| 4 | + * @return {number} |
| 5 | + */ |
| 6 | +var fillCups = function (amount) { |
| 7 | + let count = 0; |
| 8 | + // 大顶堆 |
| 9 | + const maxHeap = new MaxHeap(); |
| 10 | + |
| 11 | + for (let i = 0; i < amount.length; i++) { |
| 12 | + maxHeap.push(amount[i]); |
| 13 | + } |
| 14 | + while (true) { |
| 15 | + const first = maxHeap.pop(); |
| 16 | + const second = maxHeap.pop(); |
| 17 | + |
| 18 | + if (second === 0) { |
| 19 | + count += first; |
| 20 | + break; |
| 21 | + } |
| 22 | + count++; |
| 23 | + maxHeap.push(first - 1); |
| 24 | + maxHeap.push(second - 1); |
| 25 | + } |
| 26 | + |
| 27 | + return count; |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * 优先队列 - 堆 |
| 32 | + * 对外暴露接口: |
| 33 | + * - push: 向队尾添加元素 |
| 34 | + * - pop: 从队头取出元素 |
| 35 | + */ |
| 36 | +class MaxHeap { |
| 37 | + constructor() { |
| 38 | + this.queue = []; |
| 39 | + } |
| 40 | + |
| 41 | + push(item) { |
| 42 | + this.queue.push(item); |
| 43 | + // 上移 |
| 44 | + this.siftUp(this.size() - 1); |
| 45 | + } |
| 46 | + |
| 47 | + pop() { |
| 48 | + if (this.size() === 0) { |
| 49 | + return; |
| 50 | + } |
| 51 | + if (this.size() === 1) { |
| 52 | + return this.queue.pop(); |
| 53 | + } |
| 54 | + const removedItem = this.queue[0]; |
| 55 | + this.queue[0] = this.queue.pop(); |
| 56 | + // 下沉 |
| 57 | + this.siftDown(0); |
| 58 | + |
| 59 | + return removedItem; |
| 60 | + } |
| 61 | + |
| 62 | + // 上移 |
| 63 | + siftUp(index) { |
| 64 | + const parent = index === 0 ? null : (index - 1) >> 1; |
| 65 | + |
| 66 | + if (index > 0 && this.queue[index] > this.queue[parent]) { |
| 67 | + swap(this.queue, index, parent); |
| 68 | + this.siftUp(parent); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + // 下沉 |
| 73 | + siftDown(index) { |
| 74 | + const left = index * 2 + 1; |
| 75 | + const right = index * 2 + 2; |
| 76 | + const size = this.size(); |
| 77 | + let last = index; |
| 78 | + |
| 79 | + if (left < size && this.queue[left] > this.queue[last]) { |
| 80 | + last = left; |
| 81 | + } |
| 82 | + if (right < size && this.queue[right] > this.queue[last]) { |
| 83 | + last = right; |
| 84 | + } |
| 85 | + |
| 86 | + if (last !== index) { |
| 87 | + swap(this.queue, index, last); |
| 88 | + this.siftDown(last); |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + size() { |
| 93 | + return this.queue.length; |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +function swap(arr, i, j) { |
| 98 | + const temp = arr[i]; |
| 99 | + arr[i] = arr[j]; |
| 100 | + arr[j] = temp; |
| 101 | +} |
0 commit comments