Leetcode 347: Top K Frequent Elements

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 347: Top K Frequent Elements相关的知识,希望对你有一定的参考价值。

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note: 

    • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
    • Your algorithm‘s time complexity must be better than O(n log n), where n is the array‘s size.
 1 public class Solution {
 2     public IList<int> TopKFrequent(int[] nums, int k) {
 3         var dict = new Dictionary<int, int>();
 4         
 5         foreach (var n in nums)
 6         {
 7             if (!dict.ContainsKey(n))
 8             {
 9                 dict[n] = 0;
10             }
11             
12             dict[n]++;
13         }
14         
15         var freq = new List<int>[nums.Length + 1];
16         
17         foreach (var kv in dict)
18         {
19             if (freq[kv.Value] == null)
20             {
21                 freq[kv.Value] = new List<int>();
22             }
23             
24             freq[kv.Value].Add(kv.Key);
25         }
26         
27         var result = new List<int>();
28         for (int i = nums.Length; i >= 0; i--)
29         {
30             if (freq[i] != null)
31             {
32                 foreach (var v in freq[i])
33                 {
34                     result.Add(v);
35                     if (result.Count >= k) return result;
36                 }
37             }
38         }
39         
40         return result;
41     }
42 }

 


以上是关于Leetcode 347: Top K Frequent Elements的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 347. Top K Frequent Elements

Leetcode 347: Top K Frequent Elements

LeetCode OJ 347. Top K Frequent Elements hashmap+排序求解

leetcode347 - Top K Frequent Elements - medium

Leetcode_347_Top K Frequent Elements

Leetcode_347_Top K Frequent Elements