-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminOpToExceedThresholdII.js
More file actions
107 lines (90 loc) · 2.36 KB
/
minOpToExceedThresholdII.js
File metadata and controls
107 lines (90 loc) · 2.36 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
function minOperations(nums, k) {
/**
* Min-heap implementation (since JavaScript doesn't have a built-in one)
*/
class MinPriorityQueue {
constructor() {
this.heap = [];
}
enqueue(value) {
this.heap.push(value);
this.bubbleUp(this.heap.length - 1);
}
dequeue() {
if (this.isEmpty()) {
return null;
}
if (this.heap.length === 1) {
return this.heap.pop();
}
const min = this.heap[0];
this.heap[0] = this.heap.pop();
this.sinkDown(0);
return min;
}
peek() {
return this.isEmpty() ? null : this.heap[0];
}
isEmpty() {
return this.heap.length === 0;
}
size() {
return this.heap.length;
}
bubbleUp(index) {
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if (this.heap[index] >= this.heap[parentIndex]) {
break;
}
this.swap(index, parentIndex);
index = parentIndex;
}
}
sinkDown(index) {
const length = this.heap.length;
while (true) {
let leftChildIndex = 2 * index + 1;
let rightChildIndex = 2 * index + 2;
let smallest = index;
if (
leftChildIndex < length &&
this.heap[leftChildIndex] < this.heap[smallest]
) {
smallest = leftChildIndex;
}
if (
rightChildIndex < length &&
this.heap[rightChildIndex] < this.heap[smallest]
) {
smallest = rightChildIndex;
}
if (smallest === index) {
break;
}
this.swap(index, smallest);
index = smallest;
}
}
swap(i, j) {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
}
const minHeap = new MinPriorityQueue();
for (const num of nums) {
minHeap.enqueue(num);
}
let operations = 0;
while (minHeap.size() >= 2 && minHeap.peek() < k) {
const x = minHeap.dequeue();
const y = minHeap.dequeue();
minHeap.enqueue(Math.min(x, y) * 2 + Math.max(x, y));
operations++;
}
return operations;
}