c# - 如何使查找数组中第 N 个最频繁元素的过程更加高效和紧凑?

标签 c# .net algorithm linq

这是我想出的解决方案的示例

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        int[] arr = new int[] { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 }; 
        var countlist = arr.Aggregate(new Dictionary<int,int>(), (D,i) => { 
                                        D[i] = D.ContainsKey(i) ? (D[i] + 1) : 1;
                                        return D; 
                                      })
                            .AsQueryable()
                            .OrderByDescending(x => x.Value)
                            .Select(x => x.Key)
                            .ToList();
        // print the element which appears with the second 
        // highest frequency in arr
        Console.WriteLine(countlist[2]); // should print 3
    }
}

至少,我想弄清楚如何去做

  • 至少减少一个查询子句。虽然我没有看到任何冗余,但这是 LINQ 查询的类型,我担心创建的所有中间结构的所有开销。

  • 弄清楚如何在最后不返回整个列表。我只想要枚举序列中的第二个元素;我不需要为了从中获取单个元素而返回整个列表。

最佳答案

int[] arr = new int[] { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };

var lookup = arr.ToLookup(t => t);
var result = lookup.OrderByDescending(t => t.Count());

Console.WriteLine(result.ElementAt(1).Key);

关于c# - 如何使查找数组中第 N 个最频繁元素的过程更加高效和紧凑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38006865/

相关文章:

c# - ASP.NET Core 中的模型绑定(bind)以将下划线映射到首字母大写属性名称

c# - 如何使用 Linq to Xml 获取单个 XElement 对象?

c# - 以下通过关闭取消订阅事件的模式会导致任何问题吗?

c# - WCF 服务中的操作筛选器

c# - 为 500,000 个航类寻找航类连通性的算法

algorithm - 如何将此类 DFS 算法问题扩展/分布到分布式系统中

c# - 首先在 EF4.1 代码中,使用注释、配置文件或在 OnModelCreating 中配置实体有什么区别?

c# - 尝试项目示例 "HelloAR",构建成功但手机上没有任何显示

c# - 找不到存储过程 dbo asp net 检查架构版本 LOCALHOST

php - 长位随机数生成算法