每日一题 -- 堆
719. 找出第 k 小的距离对
719. 找出第 k 小的距离对
分析
- 使用双遍历+堆找第 k 小超时
- 使用这种多路归并还是超时了,所以后面再看看这么弄
var smallestDistancePair = function (nums, k) {
const minHeap = new Heap()
nums = nums.sort((a, b) => a - b)
for (let i = 0; i < nums.length - 1; i++) {
minHeap.heappush(nums[i + 1] - nums[i], i, i + 1)
}
while (--k) {
const [val, from, to] = minHeap.heappop()
if (to + 1 < nums.length) {
minHeap.heappush(nums[to + 1] - nums[from], [from, to + 1])
}
}
return minHeap.data[1]
};
const Heap = function () {
this.data = []
this.data.push(0)
}
Heap.prototype.heappush = function (val, fr, to) {
this.data.push([val, fr, to])
this.data[0] += 1
this.up(this.data[0])
}
Heap.prototype.heappop = function () {
if (this.data[0] !== 1) {
this.swap(1, this.data[0])
}
const res = this.data.pop()
this.data[0] -= 1
this.down()
return res
}
Heap.prototype.swap = function (a, b) {
let temp = this.data[a]
this.data[a] = this.data[b]
this.data[b] = temp
}
Heap.prototype.down = function (index = 1) {
if (index * 2 > this.data[0]) return
const left = 2 * index
const right = 2 * index + 1
let target = index
if (left <= this.data[0] && this.data[left][0] < this.data[target][0]) {
target = left
}
if (right <= this.data[0] && this.data[right][0] < this.data[target][0]) {
target = right
}
if (target !== index) {
this.swap(target, index)
this.down(target)
}
}
Heap.prototype.up = function (index) {
if (index < 2) return
const fatherIndex = Math.floor(index / 2)
if (this.data[index][0] < this.data[fatherIndex][0]) {
this.swap(index, fatherIndex)
this.up(fatherIndex)
}
}