首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用LINQ选择数组中最小、最常见的数字

使用LINQ选择数组中最小、最常见的数字
EN

Stack Overflow用户
提问于 2017-12-29 04:05:29
回答 3查看 1.6K关注 0票数 2

如果我有一个没有排序的数组,其中有多对相同的数字,我如何才能找到最小的最常见的数字?

代码语言:javascript
运行
复制
int[] arr = new int[] {8, 6, 5, 2, 5, 9, 6, 9, 2, 3}; // unsorted array
// Array.Sort(arr); // I could sort the array

int mostCommon =  arr.GroupBy(ii => ii)  //Grouping same items
            .OrderByDescending(abc => abc.Count()) //now getting frequency of a value
            .Select(bcd => bcd.Key) //selecting key of the group
            .FirstOrDefault();   //Finally, taking the most frequent value

在上述情况下,我希望得到2,但是查询返回6。如果在运行查询之前对数组进行排序,我将得到2,但我想知道是否有一种方法可以使用LINQ从未排序的数组中获取最小的最常见值。我对代码的快速执行并不感兴趣。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-12-29 04:11:18

有两个2's,2个6's和2个9's --假设您的意思是,在领带的情况下,最低的(2)应该具有优先级,那么您只需要添加第二个顺序,如下所示:

代码语言:javascript
运行
复制
int mostCommon = arr.GroupBy(x => x)
            .OrderByDescending(grp => grp.Count()) // First precedence = frequency
            .ThenBy(grp => grp.Key) // Second precedence is lowest number first
            .Select(bcd => bcd.Key)
            .FirstOrDefault();

编辑,re O(N)解

这里有一种方法,使用命令式的方法,这可以在一次通过数据完成。考虑到您已经在数组中指定了个位数,我假设bin计数数组的范围为0-10 (其好处是值被初始化为零),但是如果范围更大,显然会进行调整。如果您的值很大并且很可能是稀疏的,那么您可能需要用字典代替数组。

代码语言:javascript
运行
复制
var bins = new int[10]; // Adjust this to size / use Dictionary if sparse
var hiCount = 0;
var smallestMostCommon = int.MaxValue;
foreach(var a in arr)
{
   var newCount = ++bins[a];
   if (newCount > hiCount) // 1st Precedence : Frequency
   {
      hiCount = newCount;
      smallestMostCommon = a;
   }
   else if (newCount == hiCount && a < smallestMostCommon) // 2nd : Lowest preferred
   {
      smallestMostCommon = a;
   }
}

我确信,进一步的优化是可能的,特别是在循环的任何一点上,如果剩余的元素数小于第一和第二最高回收箱之间的差,那么循环可以提前结束。

票数 3
EN

Stack Overflow用户

发布于 2017-12-29 04:11:54

您需要在Select之前再次订购项,这样FirstOrDefault将返回最小的组键:

代码语言:javascript
运行
复制
int smallestMostCommon =  arr.GroupBy(ii => ii)  //Grouping same items
        .OrderByDescending(abc => abc.Count()) //now getting frequency of a value
        .ThenBy(g => g.Key) // Make sure we get the smallest key first
        .Select(bcd => bcd.Key) //selecting key of the group
        .FirstOrDefault();   //Finally, taking the most frequent value
票数 3
EN

Stack Overflow用户

发布于 2017-12-29 05:16:08

使用排序算法按数字顺序排序数组中的值。搜索‘气泡分类’。我喜欢循环这个算法以确保准确性。然后对产品执行相同的排序,以确定相似的值,并打印结果。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48017250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档