347. 前 K 個高頻元素

給定一個非空的整數(shù)數(shù)組,返回其中出現(xiàn)頻率前 k 高的元素。

示例 1:

輸入: nums = [1,1,1,2,2,3], k = 2
輸出: [1,2]
示例 2:

輸入: nums = [1], k = 1
輸出: [1]
說明:

你可以假設給定的 k 總是合理的,且 1 ≤ k ≤ 數(shù)組中不相同的元素的個數(shù)。
你的算法的時間復雜度必須優(yōu)于 O(n log n) , n 是數(shù)組的大小。

type number struct {
    number int
    ncount int
}

// An IntHeap is a min-heap of ints.
type IntHeap []number

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i].ncount < h[j].ncount }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

// Push ...
func (h *IntHeap) Push(x interface{}) {
    // Push and Pop use pointer receivers because they modify the slice's length,
    // not just its contents.
    *h = append(*h, x.(number))
}

// Pop ...
func (h *IntHeap) Pop() interface{} {
    old := *h
    n := len(old)
    x := old[n-1]
    *h = old[0 : n-1]
    return x
}

func topKFrequent(nums []int, k int) []int {
    numberMap := make(map[int]int, 0)
    for i := 0; i < len(nums); i++ {
        if _, exist := numberMap[nums[i]]; !exist {
            numberMap[nums[i]] = 1
            continue
        }
        numberMap[nums[i]]++
    }
    h := new(IntHeap)
    for n, count := range numberMap {
        heap.Push(h, number{number: n, ncount: count})
        if h.Len() > k {
            heap.Pop(h)
        }
    }
    numss := make([]int, 0)
    for i := 0; i < h.Len(); i++ {
        numss = append(numss, (*h)[i].number)
    }
    return numss
}

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容