版权声明: 本文为博主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.

C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解的更多相关文章

  1. [leetcode]347. Top K Frequent Elements K个最常见元素

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  2. [LeetCode] 347. Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  3. Leetcode 347. Top K Frequent Elements

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  4. [LeetCode] 347. Top K Frequent Elements 解题思路 - Java

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  5. [leetcode]347. Top K Frequent Elements 最高频的前K个元素

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  6. Java [Leetcode 347]Top K Frequent Elements

    题目描述: Given a non-empty array of integers, return the k most frequent elements. For example,Given [1 ...

  7. C#版[击败99.69%的提交] - Leetcode 242. 有效的同构异形词 - 题解

    C#版 - Leetcode 242. 有效的同构异形词 - 题解 Leetcode 242.Valid Anagram 在线提交: https://leetcode.com/problems/val ...

  8. 【leetcode】347. Top K Frequent Elements

    题目地址:https://leetcode.com/problems/top-k-frequent-elements/ 从一个数组中求解出现次数最多的k个元素,本质是top k问题,用堆排序解决. 关 ...

  9. 【LeetCode】347. Top K Frequent Elements 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 解题方法 字典 优先级队列 日期 题目地址:https://l ...

随机推荐

  1. PTA L2-011 玩转二叉树 二叉树+bfs

    思路: 先建树,然后按层次输出. #include<iostream> #include<cstring> #include<cstdio> #include< ...

  2. 8080端口被System占用

    System是Windows页面内存管理进程,拥有0级优先权,没有它系统无法启动 就是说,System进程是无法关闭的,所以不要尝试去强行关闭,可能引起电脑异常查看是否是IIS占用的, 进入电脑控制面 ...

  3. 动态规划——Palindrome Partitioning II

    Palindrome Partitioning II 这个题意思挺好理解,提供一个字符串s,将s分割成多个子串,这些字串都是回文,要求输出分割的最小次数. Example:Input: "a ...

  4. 匿名函数 javascript

    匿名函数: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

  5. 关于H5的一些杂思细想(一)

    作为一名前端程序媛,虽然整天和代码打交道,但是还是有一颗小清新的内心,虽然有时候加起班来不是人,但是空闲的时候还是会整理一下思绪,顺便整理一下自己,两个多月的加班,一直没有更新,今天就把自己最近做的一 ...

  6. python学习:字符串

    字符串 #字符串操作# 对应操作:# 1.重复输出字符串# print('hello'*2)# 2.[],[:]通过索引获取字符串中字符,这里和列表的切片操作是相同的,具体内容见列表#print('h ...

  7. kodexplorer免费网盘安装教程

    KodExplorer是什么? KodExplorer可道云,原名芒果云,是基于Web技术的私有云和在线文件管理系统. 用户只需通过简单环境搭建,即可使用KodExplorer快速完成私有云/私有网盘 ...

  8. spring-cloud-Zuul学习(二)【基础篇】--典型配置【重新定义spring cloud实践】

    -- 2019-04-15 20:22:34 引言 上一节是一个最基本的zuul网关实例,它是整个spring-cloud生态里面“路由-服务”的一个缩影,后续也就是锦上添花.这节主要讲述zuul的一 ...

  9. 01.在vue中通过 JSONP 方式来跨域

    //1.引入 : 在main.js 中引入该文件即可 //2.使用: axios.jsonp('地址').then(res => { // console.log(res) // } impor ...

  10. day11函数(形参实参)

    形参与实参 def fn(形参们): pass # 形参:定义函数,在括号内声明的变量名,用来结束外界传来的值# 实参:调用函数,在括号内传入的实际值,值可以为常量.变量.表达式或三者的组合 # 注: ...