码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 347: Top K Frequent Elements

时间:2017-12-13 11:38:57      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:etc   note   log   pre   new   list   bsp   size   turn   

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

标签:etc   note   log   pre   new   list   bsp   size   turn   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!