首页 > 其他 > 详细

Leetcode 347: Top K Frequent Elements

时间:2017-12-13 10:43:42      阅读:178      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/liangmou/p/8030652.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!