如果我有一个没有排序的数组,其中有多对相同的数字,我如何才能找到最小的最常见的数字?
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从未排序的数组中获取最小的最常见值。我对代码的快速执行并不感兴趣。
发布于 2017-12-29 04:11:18
有两个2's,2个6's和2个9's --假设您的意思是,在领带的情况下,最低的(2)应该具有优先级,那么您只需要添加第二个顺序,如下所示:
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 (其好处是值被初始化为零),但是如果范围更大,显然会进行调整。如果您的值很大并且很可能是稀疏的,那么您可能需要用字典代替数组。
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;
   }
}我确信,进一步的优化是可能的,特别是在循环的任何一点上,如果剩余的元素数小于第一和第二最高回收箱之间的差,那么循环可以提前结束。
发布于 2017-12-29 04:11:54
您需要在Select之前再次订购项,这样FirstOrDefault将返回最小的组键:
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发布于 2017-12-29 05:16:08
使用排序算法按数字顺序排序数组中的值。搜索‘气泡分类’。我喜欢循环这个算法以确保准确性。然后对产品执行相同的排序,以确定相似的值,并打印结果。
https://stackoverflow.com/questions/48017250
复制相似问题