题目
- 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
- leetcode链接:https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/
思路
- 大顶堆,维护容量为K的大顶堆,先对前k个数创建大顶堆,然后从第k+1个数开始,看是否比堆顶小,是的话就将这个数和堆顶交换,并从新调整为大顶堆
代码
/**
* @param {number[]} arr
* @param {number} k
* @return {number[]}
*/
var getLeastNumbers = function (arr, k) {
if (arr.length <= k) return arr
const heap = new BigHeap()
for (let i = 0; i < arr.length; i++) {
if (i <= k - 1) {
heap.insert(arr[i])
} else {
heap.update(arr[i])
}
}
return heap.getResult()
}
function BigHeap() {
this.queue = [null]
}
BigHeap.prototype.update = function(x) {
if (x < this.queue[1]) {
this.queue[1] = x
this.heapify()
}
}
BigHeap.prototype.insert = function(x) {
this.queue.push(x)
let index = this.queue.length - 1
while (Math.floor(index / 2) > 0 && this.queue[index] > this.queue[Math.floor(index / 2)]) {
swap(this.queue, Math.floor(index / 2), index)
index = Math.floor(index / 2)
}
}
BigHeap.prototype.heapify = function() {
let i = 1
while (i < this.queue.length) {
let maxIndex = i
if (2 * i < this.queue.length && this.queue[2 * i] > this.queue[maxIndex]) {
maxIndex = 2 * i
}
if (2 * i + 1 < this.queue.length && this.queue[2 * i + 1] > this.queue[maxIndex]) {
maxIndex = 2 * i + 1
}
if (maxIndex === i) break
swap(this.queue, maxIndex, i)
i = maxIndex
}
}
BigHeap.prototype.getResult = function() {
return this.queue.slice(1)
}
function swap(arr, i, j) {
const temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}