如何使查找数组中第N个最频繁元素的过程更高效,更紧凑? [英] How can I make my procedure for finding the Nth most frequent element in an array more efficient and compact?
本文介绍了如何使查找数组中第N个最频繁元素的过程更高效,更紧凑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我想出的解决方案的一个例子
Here's an example of a solution I came up with
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查询的类型,在这里我担心创建的所有中间结构的所有开销。
Cut down the query clauses by at least one. While I don't see any redundancy, this is the type of LINQ query where I fret about all the overhead of all the intermediate structures created.
弄清楚如何不在末尾返回整个列表。我只想列举序列中的第二个元素;我不需要出于从列表中删除单个元素的目的而返回整个列表。
Figure out how to not return an entire list at the end. I just want the 2nd element in the enumerated sequence; I shouldn't need to return the entire list for the purpose of getting a single element out of it.
推荐答案
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);
这篇关于如何使查找数组中第N个最频繁元素的过程更高效,更紧凑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文