题解 | #最小的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小数#
全部评论

相关推荐

程序员牛肉:你这简历有啥值得拷打的?在牛客你这种简历一抓一大把,也就是个人信息不一样而已。 关键要去找亮点,亮点啊,整个简历都跟流水线生产出来的一样。
点赞 评论 收藏
分享
_mos_:要不是看评论区我都不知道你要找的是数分
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务