1. 程式人生 > 其它 >leetcode347.前K個高頻元素

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)
            }
        }
    }
};