剑指OFFER----40-1、最小的K个数(js实现)

题目


思路

  • 大顶堆,维护容量为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
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值