Leetcode刷题(第347题)——前K个高频元素

x33g5p2x  于2022-03-28 转载在 其他  
字(1.7k)|赞(0)|评价(0)|浏览(316)

一、题目

  1. 给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你
  2. 可以按 任意顺序 返回答案。

二、示例

  1. 输入: nums = [1,1,1,2,2,3], k = 2
  2. 输出: [1,2]
  1. 输入: nums = [1], k = 1
  2. 输出: [1]

三、思路
本题采用的算法思路是最小堆。
四、代码展示

  1. /**
  2. * @param {number[]} nums
  3. * @param {number} k
  4. * @return {number[]}
  5. */
  6. class MinHeap {
  7. constructor() {
  8. this.heap = []
  9. }
  10. addOne(value) {
  11. this.heap.push(value)
  12. this.shiftUp(this.heap.length - 1)
  13. }
  14. shiftUp(index) {
  15. if (index === 0) return
  16. let parentIndex = this.getParentIndex(index)
  17. if (this.heap[parentIndex] && this.heap[index] && this.heap[parentIndex].value > this.heap[index].value) {
  18. this.swap(index, parentIndex)
  19. this.shiftUp(parentIndex)
  20. }
  21. }
  22. getParentIndex(index) {
  23. return Math.floor((index - 1) / 2)
  24. }
  25. swap(index1, index2) {
  26. let temp = this.heap[index1]
  27. this.heap[index1] = this.heap[index2]
  28. this.heap[index2] = temp
  29. }
  30. pop() {
  31. if (this.heap.length <= 1) {
  32. this.heap.shift()
  33. return
  34. }
  35. this.heap[0] = this.heap.pop()
  36. this.shiftDown(0)
  37. }
  38. shiftDown(index) {
  39. let leftChildIndex = this.getLeftChildIndex(index)
  40. let rightChildIndex = this.getRightChildIndex(index)
  41. if (this.heap[leftChildIndex] && this.heap[index] && this.heap[leftChildIndex].value < this.heap[index].value) {
  42. this.swap(index, leftChildIndex)
  43. this.shiftDown(leftChildIndex)
  44. }
  45. if (this.heap[rightChildIndex] && this.heap[index] && this.heap[rightChildIndex].value < this.heap[index].value) {
  46. this.swap(index, rightChildIndex)
  47. this.shiftDown(rightChildIndex)
  48. }
  49. }
  50. getLeftChildIndex(index) {
  51. return index * 2 + 1
  52. }
  53. getRightChildIndex(index) {
  54. return index * 2 + 2
  55. }
  56. size() {
  57. return this.heap.length
  58. }
  59. }
  60. var topKFrequent = function (nums, k) {
  61. let map = new Map()
  62. let newHeap = new MinHeap()
  63. for (let item of nums) {
  64. if (map.has(item)) {
  65. map.set(item, map.get(item) + 1)
  66. } else {
  67. map.set(item, 1)
  68. }
  69. }
  70. map.forEach((value, key) => {
  71. newHeap.addOne({ value, key })
  72. if (newHeap.size() > k) {
  73. newHeap.pop()
  74. }
  75. })
  76. return newHeap.heap.map((item) => item.key)
  77. };

五、总结

相关文章