347 Top K Frequent Elements
2016-05-11 15:33
399 查看
题目:给定一个数组,输出频度最高的K个数。
解题思路:建立一个字典<数,数的频度>,将字典按value的降序排序,然后输出前K个数。
重点:Dictionary的降序排序(一般来说,对字典排序使没有意义的)
public class Solution { public IList<int> TopKFrequent(int[] nums, int k) { Dictionary<int, int> numFrequency = new Dictionary<int, int>(); for (int i = 0; i < nums.Length; i++) { if (numFrequency.ContainsKey(nums[i])) numFrequency[nums[i]]++; else { numFrequency.Add(nums[i], 1); } } var results = numFrequency.OrderByDescending(o => o.Value).ToDictionary(o=>o.Key,v=>v.Value); List<int> kNums = new List<int>(); int j = 0; foreach(int key in results.Keys) { j++; if (j <= k) kNums.Add(key); } return kNums; } }
相关文章推荐
- easyui from 缓存问题处理
- UIAlertController 使用
- Android关于buildToolVersion与CompileSdkVersion的区别
- 62. Unique Paths
- dequeueReusableCellWithIdentifier 总是返回nil
- iOS UIDevice设备信息,传感器设置,横竖屏判断操作,手机电池操作
- 自定义UICollectionViewLayout实现瀑布流
- OGG由于GGS处理SEQUENCE方式导致Ext延时_NOAUTOMATICSEQUENCEFLUSH处理
- IOS开发-UIView之动画效果的实现方法(合集)
- Executors.newFixedThreadPool和ArrayBlockingQueue一点使用心得
- iOS开发之基础视图——UILabel
- UITextField 控制文本输入小数点和小数点后几位
- django1.8 提示(1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your defau
- iOS开发 贝塞尔曲线UIBezierPath(后记)
- 学习笔记-UITableView的数据源(dataSource)和代理(delegate)
- iOS开发 贝塞尔曲线UIBezierPath
- Android开发之蓝牙(Bluetooth)操作(一)--扫描已经配对的蓝牙设备
- easyUI中tab中的html片段导包与父页面的包冲突
- 【FLUENT案例】06:与EDEM耦合计算
- 【代码】key-value模式下的哈希二次探测与简单的哈希类的实现