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

2023-12-21

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

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使查找数组中第 N 个最频繁元素的过程更加高效和紧凑? 的相关文章

随机推荐