2
* @param {number[]} nums13
* @param {number[]} nums28
var kSmallestPairs = function (nums1, nums2, k) {9
const h = new MinHeap();11
for (i = 0; i < nums1.length; i++)12
h.push({ id: nums1[i] + nums2[0], i: i, j: 0 });18
res.push([nums1[i], nums2[j]]);19
if (j < nums2.length - 1)20
h.push({ id: nums1[i] + nums2[j + 1], i, j: j + 1 });26
This is a heap class that I wrote it myself,29
bug? IDK (tested a few times for both min and max heaps)30
so use it at your own risk :)33
constructor(arr = [], sortKey = null) {35
this.sortKey = sortKey;36
if (arr && arr.length) this.buildHeap(arr);41
this.heapUp(this.heap.length - 1);45
if (!this.heap.length) return null;46
if (this.heap.length == 1) return this.heap.pop();47
const res = this.heap[0];48
this.heap[0] = this.heap.pop();54
if (this.sortKey !== null) return this.heap[i][this.sortKey];59
const t = this.heap[i];60
this.heap[i] = this.heap[j];63
/*for child class to implement*/74
for (let i of list) this.push(i);82
class MinHeap extends Heap {84
const pI = (i - 1) >> 1;86
if (this.id(i) < this.id(pI)) {88
return this.heapUp(pI);95
if (lI >= this.heap.length) return;99
rI >= this.heap.length ? Number.MAX_VALUE : this.id(rI)101
if (v == this.id(i)) return;102
if (v == this.id(lI)) {104
return this.heapDown(lI);111
class MaxHeap extends Heap {113
const pI = (i - 1) >> 1;115
if (this.id(i) > this.id(pI)) {117
return this.heapUp(pI);122
const lI = i * 2 + 1;123
const rI = i * 2 + 2;124
if (lI >= this.heap.length) return;128
rI >= this.heap.length ? Number.MIN_VALUE : this.id(rI)130
if (v == this.id(i)) return;131
if (v == this.id(lI)) {133
return this.heapDown(lI);