leetcode347.前K个高频元素
leetcode347.前K个高频元素
题目
给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。
用例
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
输入: nums = [1], k = 1
输出: [1]
求解
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var topKFrequent = function(nums, k) {
//存放堆中的位置和频率
let frequency={}
//存放元素的堆
let heap = []
//结果
let res = []
for(let i=0;i<nums.length;i++){
//如果已经计数过了
if(frequency[nums[i]]){
frequency[nums[i]][1]=frequency[nums[i]][1]+1
//更新堆
UpHeap(frequency[nums[i]][0])
}else{
frequency[nums[i]]=[heap.length,1]
//放入堆中
heap.push(nums[i])
}
}
for(let i=0;i<k;i++){
res.push(heap[0])
//更新堆
frequency[heap[0]][1]=0
DownHeap(0)
}
return res
function UpHeap(index){
if(index>0){
let father = Math.ceil(index/2)-1
//爸爸小了
if(frequency[heap[father]][1]<frequency[heap[index]][1]){
//frequency中修改存放位置
frequency[heap[father]][0]=index
frequency[heap[index]][0]=father
//交换堆中位置
tmp=heap[father]
heap[father]=heap[index]
heap[index]=tmp
//进行下一步比较
UpHeap(father)
}else{
return
}
}
}
function DownHeap(index){
let son1=index*2+1
let son2=index*2+2
if(son1>heap.length-1){
return
}
if(son2>heap.length-1){
son2=son1
}
//获取频率值进行比较,选取高的
if(frequency[heap[son1]][1]>=frequency[heap[son2]][1]){
//如果频率值高的要比父亲大那么换位
if(frequency[heap[son1]][1]>frequency[heap[index]][1]){
frequency[heap[son1]][0]=index
frequency[heap[index]][0]=son1
tmp=heap[son1]
heap[son1]=heap[index]
heap[index]=tmp
DownHeap(son1)
}
}else{
if(frequency[heap[son2]][1]>frequency[heap[index]][1]){
frequency[heap[son2]][0]=index
frequency[heap[index]][0]=son2
tmp=heap[son2]
heap[son2]=heap[index]
heap[index]=tmp
DownHeap(son2)
}
}
}
};

浙公网安备 33010602011771号