题解 | #最小的K个数#
最小的K个数
https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
using System;
using System.Collections.Generic;
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param input int整型一维数组
* @param k int整型
* @return int整型一维数组
*/
SortedDictionary<int, int> sortDic = new
SortedDictionary<int, int>();//键表示对应数字,值表示对应数字在数组中出现的次数
public List<int> GetLeastNumbers_Solution(List<int> input, int k) {
// write code here
if (input.Count == 0 || k == 0) return new List<int>();
if (input.Count < k) return new List<int>();
List<int> res = new List<int>();
for (int i = 0; i < input.Count; i++) {
if (sortDic.ContainsKey(input[i])) {
sortDic[input[i]] += 1;
} else {
sortDic.Add(input[i], 1);
}
}
int j = 0;
foreach (KeyValuePair<int, int> item in sortDic) {
int temp = item.Value;//每个元素的次数
while (temp != 0 && j < k) {
res.Add(item.Key);
++j;
--temp;
}
}
return res;
}
}
#有序字典求前k小数#

