C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解

版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址
http://blog.csdn.net/lzuacm

C#版 - Leetcode 347. Top K Frequent Elements - 题解

在线提交: https://leetcode.com/problems/top-k-frequent-elements/

Description


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.


思路:
使用字典Dictionary<int, int>存储每个数出现的次数,并对次数进行排序。有两种方法;
1.将Dictionary转为List,实现Sort的CompareTo方法;
2.使用Dictionary的OrderByDescending(f => f.value),并Take(k)。
由于转换为List后进行排序会让程序速度变慢,建议直接用后一种方法。

已AC代码:

public class Solution
{
    public IList<int> TopKFrequent(int[] nums, int k)
    {
        var dict = new Dictionary<int, int>();
        IList<int> result = new List<int>();
        foreach (var num in nums)
        {
            if (!dict.ContainsKey(num))
                dict.Add(num, 1);
            else dict[num]++;
        }
        var list = dict.ToList();
        list.Sort((x, y) => -x.Value.CompareTo(y.Value));

        if (list.Count >= k)
        {
            for (int i = 0; i < k; i++)
            {
                result.Add(list.ElementAtOrDefault(i).Key);
            }
        }           

        return result;
    }
}

改进版:

public class Solution
{
    public IList<int> TopKFrequent(int[] nums, int k)
    {
        var dict = new Dictionary<int, int>();
        IList<int> result = new List<int>();
        foreach (var num in nums)
        {
            if (!dict.ContainsKey(num))
                dict.Add(num, 1);
            else dict[num]++;
        }
        var list = dict.OrderByDescending(f => f.Value).Take(k).ToList();

        for (int i = 0; i < k; i++)
            result.Add(list.ElementAtOrDefault(i).Key);     

        return result;
    }
}

Rank:

You are here!
Your runtime beats 99.28 % of csharp submissions.

全部评论

相关推荐

不愿透露姓名的神秘牛友
04-30 11:43
春招失败、父母离婚,好像我的人生一团糟,一年来压力大到常常崩溃。不知道能跟谁聊,朋友其实对我非常好,但是她无意中表达出来的家庭幸福都会刺痛到我……和ai聊天,我的未来在更高处,不在楼下,忍不住爆哭😭
youngfa:害,妹妹,我是一个研究生(很上进很想找到好工作的那种),但去年因为生病回家休养错过了秋招(当时对我的冲击也是非常大的),这学期返校来了也是把论文盲审交了后才开始找工作,现在也是一个offer没有,但我就没有像你一样把这个阶段性的事情绑定到人生上,人生不仅很长,也很广阔,先停下来,放松一下哦。不要被外部环境灌输的思维操控了,好好爱自己!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务