LeetCode Explanation Chapter 347. Top K high-frequency elements

347. Top K high-frequency elements

Question description

describe

Problem solving ideas

Sort the array in reverse order according to frequency, and then return the top k data

Solution code

func topKFrequent(nums []int, k int) []int {
    
    
  m := make(map[int]int, 0)
  for i := len(nums) - 1; i >= 0; i-- {
    
    
    m[nums[i]]++
  }
  res := make([]int, 0, len(m))
  for k, _ := range m {
    
    
    res = append(res, k)
  }
  // 降序
  sort.Slice(res, func(a, b int) bool {
    
    
    return m[res[a]] > m[res[b]]
  })
  return res[:k]
}

Supongo que te gusta

Origin blog.csdn.net/qq_67733273/article/details/133233915
Recomendado
Clasificación