版权声明: 本文为博主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. docker-compose.yml 配置文件详解及项目发布

    摘自:https://blog.csdn.net/qq_36148847/article/details/79427878 docker部署tomcat项目 1.上传war包2.制作镜像 Docker ...

  2. setParameter不支持传统的按位置查询方式

    setParameter不支持传统的按位置查询方式 String hql = "from Customer as c where c.cust_id = ?"; List<C ...

  3. 可变参数函数(stdarg.h)的使用

    2013/5/3记录: stdarg.h是C语言中C标准函数库的头文件,stdarg是由standard(标准) arguments(参数)简化而来,主要目的为让函数能够接收可变参数.   stdar ...

  4. SpringCloud教程 | 第八篇: 消息总线(Spring Cloud Bus)

    一.安装rabbitmq 二.pom父文件 <?xml version="1.0" encoding="UTF-8"?> <project x ...

  5. Javascript 的变量提升与预解析

    一.什么是变量提升 在ES6之前,JavaScript没有块级作用域(一对花括号{}即为一个块级作用域),只有全局作用域和函数作用域.变量提升即将变量声明提升到它所在作用域的最开始的部分 二.怎么实现 ...

  6. vue开发(开发环境+项目搭建)

    Vue.js是一套构建用户界面的渐进式框架.与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计.Vue 的核心库只关注视图层,并且非常容易学习,非常容易与其它库或已有项目整合.另一方面,Vu ...

  7. python d:\test.py File "<stdin>", line 1 python d:\test.py ^ SyntaxError: invalid syntax

    pyhton出错: python d:\test.py File "<stdin>", line 1 python d:\test.py ^SyntaxError: i ...

  8. Golang实现requests库

    Golang实现requests库 简单的封装下,方便使用,像python的requests库一样. Github地址 Github 支持 GET.POST.PUT.DELETE applicatio ...

  9. Sqoop葵花宝典

    Sqoop葵花宝典 基于Sqoop1.x 场景 导入流程 graph LR A[RDBMS] -->|Sqoop| B(Hive) 导出流程 graph LR A[Hive] -->|Sq ...

  10. Prometheus 企业微信报警/inhibit抑制 /静默(二)

    创建企业微信应用 注册企业微信:访问https://work.weixin.qq.com/,注册企业,随便填,不需要认证 创建应用 创建告警配置 vim /usr/local/prometheus-2 ...