347. 前 K 个高频元素
Posted 沿着路走到底
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了347. 前 K 个高频元素相关的知识,希望对你有一定的参考价值。
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
class MinHeap
constructor()
this.heap = []
swap(parentIndex, childIndex)
const temp = this.heap[parentIndex]
this.heap[parentIndex] = this.heap[childIndex]
this.heap[childIndex] = temp
getParentIndex(index)
//return Math.floor((index - 1) / 2)
return (index - 1) >> 1
getLeftIndex(index)
return index * 2 + 1
getRightIndex(index)
return index * 2 + 2
shiftUp(index)
if (index === 0) return
const parentIndex = this.getParentIndex(index)
if(this.heap[parentIndex] && this.heap[parentIndex].value > this.heap[index].value)
this.swap(parentIndex, index)
this.shiftUp(parentIndex)
shiftDown(index)
const leftIndex = this.getLeftIndex(index)
const rightIndex = this.getRightIndex(index)
if(this.heap[leftIndex] && this.heap[index].value > this.heap[leftIndex].value)
this.swap(index, leftIndex)
this.shiftDown(leftIndex)
if(this.heap[rightIndex] && this.heap[index].value > this.heap[rightIndex].value)
this.swap(index, rightIndex)
this.shiftDown(rightIndex)
insert (value)
this.heap.push(value)
this.shiftUp(this.heap.length - 1)
pop ()
this.heap[0] = this.heap.pop()
this.shiftDown(0)
peek()
return this.heap[0]
size()
return this.heap.length
/**
* @param number[] nums
* @param number k
* @return number[]
*/
var topKFrequent = function(nums, k)
const map = new Map()
nums.forEach(n =>
map.set(n, map.has(n) ? map.get(n)+1 : 1)
)
const heap = new MinHeap()
map.forEach((value, key) =>
heap.insert(value, key)
if (heap.size() > k)
heap.pop()
)
return heap.heap.map(item => item.key)
;
1
以上是关于347. 前 K 个高频元素的主要内容,如果未能解决你的问题,请参考以下文章