Loading... 这题,要么先频次统计然后小顶堆,要么频次统计后分桶,同样频次的数字放一个桶,小顶堆的时间复杂度会高一点,所以不如分桶,空间换时间。 ```go func topKFrequent(nums []int, k int) []int { n := len(nums) cnts := map[int]int{} for _, v := range nums { cnts[v]++ } buckets := make([][]int, n+1) for i, v := range cnts { if v == 0 { continue } buckets[v] = append(buckets[v], i) } res := make([]int, 0, k) for i := n; k > 0 && i > 0; i-- { if len(buckets[i]) == 0 { continue } for j := 0; k > 0 && j < len(buckets[i]); j++ { res = append(res, buckets[i][j]) k-- } } return res } ``` Last modification:July 11, 2025 © Allow specification reprint Support Appreciate the author AliPayWeChat Like 如果觉得我的文章对你有用,请随意赞赏