Skip to content

Commit c8103af

Browse files
authored
Update 373-find-k-pairs-with-smallest-sums.js
1 parent 70538c7 commit c8103af

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

373-find-k-pairs-with-smallest-sums.js

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,96 @@
1+
/**
2+
* @param {number[]} nums1
3+
* @param {number[]} nums2
4+
* @param {number} k
5+
* @return {number[][]}
6+
*/
7+
const kSmallestPairs = function (nums1, nums2, k) {
8+
const pq = new PriorityQueue((a, b) => a[0] + a[1] < b[0] + b[1])
9+
for(let i = 0; i < nums1.length && i < k; i++) {
10+
pq.push([nums1[i], nums2[0], 0])
11+
}
12+
const res = []
13+
while(k > 0 && !pq.isEmpty()) {
14+
const [e1, e2, e2i] = pq.pop()
15+
res.push([e1, e2])
16+
if(e2i + 1 < nums2.length) pq.push([e1, nums2[e2i + 1], e2i + 1])
17+
k--
18+
}
19+
20+
return res
21+
}
22+
23+
class PriorityQueue {
24+
constructor(comparator = (a, b) => a > b) {
25+
this.heap = []
26+
this.top = 0
27+
this.comparator = comparator
28+
}
29+
size() {
30+
return this.heap.length
31+
}
32+
isEmpty() {
33+
return this.size() === 0
34+
}
35+
peek() {
36+
return this.heap[this.top]
37+
}
38+
push(...values) {
39+
values.forEach((value) => {
40+
this.heap.push(value)
41+
this.siftUp()
42+
})
43+
return this.size()
44+
}
45+
pop() {
46+
const poppedValue = this.peek()
47+
const bottom = this.size() - 1
48+
if (bottom > this.top) {
49+
this.swap(this.top, bottom)
50+
}
51+
this.heap.pop()
52+
this.siftDown()
53+
return poppedValue
54+
}
55+
replace(value) {
56+
const replacedValue = this.peek()
57+
this.heap[this.top] = value
58+
this.siftDown()
59+
return replacedValue
60+
}
61+
62+
parent = (i) => ((i + 1) >>> 1) - 1
63+
left = (i) => (i << 1) + 1
64+
right = (i) => (i + 1) << 1
65+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
66+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
67+
siftUp = () => {
68+
let node = this.size() - 1
69+
while (node > this.top && this.greater(node, this.parent(node))) {
70+
this.swap(node, this.parent(node))
71+
node = this.parent(node)
72+
}
73+
}
74+
siftDown = () => {
75+
let node = this.top
76+
while (
77+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
78+
(this.right(node) < this.size() && this.greater(this.right(node), node))
79+
) {
80+
let maxChild =
81+
this.right(node) < this.size() &&
82+
this.greater(this.right(node), this.left(node))
83+
? this.right(node)
84+
: this.left(node)
85+
this.swap(node, maxChild)
86+
node = maxChild
87+
}
88+
}
89+
}
90+
91+
92+
// another
93+
194
/**
295
* @param {number[]} nums1
396
* @param {number[]} nums2

0 commit comments

Comments
 (0)