如何获取 Int 数组中最常见的值? (C#)

发布于 2024-08-29 08:34:18 字数 79 浏览 6 评论 0原文

如何使用 C# 获取 Int 数组中最常见的值

例如:数组具有以下值:1, 1, 1, 2

Ans 应该是 1

How to get the most common value in an Int array using C#

eg: Array has the following values: 1, 1, 1, 2

Ans should be 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

忆梦 2024-09-05 08:34:19
var query = (from item in array
        group item by item into g
        orderby g.Count() descending
        select new { Item = g.Key, Count = g.Count() }).First();

对于仅值而不是计数,您可以

var query = (from item in array
                group item by item into g
                orderby g.Count() descending
                select g.Key).First();

在第二个上执行 Lambda 版本:

var query = array.GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
var query = (from item in array
        group item by item into g
        orderby g.Count() descending
        select new { Item = g.Key, Count = g.Count() }).First();

For just the value and not the count, you can do

var query = (from item in array
                group item by item into g
                orderby g.Count() descending
                select g.Key).First();

Lambda version on the second:

var query = array.GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
十年不长 2024-09-05 08:34:19

一些老式的高效循环:

var cnt = new Dictionary<int, int>();
foreach (int value in theArray) {
   if (cnt.ContainsKey(value)) {
      cnt[value]++;
   } else {
      cnt.Add(value, 1);
   }
}
int mostCommonValue = 0;
int highestCount = 0;
foreach (KeyValuePair<int, int> pair in cnt) {
   if (pair.Value > highestCount) {
      mostCommonValue = pair.Key;
      highestCount = pair.Value;
   }
}

现在 mostCommonValue 包含最常见的值,而 highestCount 包含它出现的次数。

Some old fashioned efficient looping:

var cnt = new Dictionary<int, int>();
foreach (int value in theArray) {
   if (cnt.ContainsKey(value)) {
      cnt[value]++;
   } else {
      cnt.Add(value, 1);
   }
}
int mostCommonValue = 0;
int highestCount = 0;
foreach (KeyValuePair<int, int> pair in cnt) {
   if (pair.Value > highestCount) {
      mostCommonValue = pair.Key;
      highestCount = pair.Value;
   }
}

Now mostCommonValue contains the most common value, and highestCount contains how many times it occured.

爱已欠费 2024-09-05 08:34:19

我知道这篇文章很旧,但今天有人问我这个问题的反面。

LINQ 分组

sourceArray.GroupBy(value => value).OrderByDescending(group => group.Count()).First().First();

临时集合,类似于 Guffa 的:

var counts = new Dictionary<int, int>();
foreach (var i in sourceArray)
{
    if (!counts.ContainsKey(i)) { counts.Add(i, 0); }
    counts[i]++;
}
return counts.OrderByDescending(kv => kv.Value).First().Key;

I know this post is old, but someone asked me the inverse of this question today.

LINQ Grouping

sourceArray.GroupBy(value => value).OrderByDescending(group => group.Count()).First().First();

Temp Collection, similar to Guffa's:

var counts = new Dictionary<int, int>();
foreach (var i in sourceArray)
{
    if (!counts.ContainsKey(i)) { counts.Add(i, 0); }
    counts[i]++;
}
return counts.OrderByDescending(kv => kv.Value).First().Key;
神仙妹妹 2024-09-05 08:34:19
  public static int get_occure(int[] a)
    {
        int[] arr = a;
        int c = 1, maxcount = 1, maxvalue = 0;
        int result = 0;
        for (int i = 0; i < arr.Length; i++)
        {
            maxvalue = arr[i];
            for (int j = 0; j <arr.Length; j++)
            {

                if (maxvalue == arr[j] && j != i)
                {
                    c++;
                    if (c > maxcount)
                    {
                        maxcount = c;
                        result = arr[i];

                    }
                }
                else
                {
                    c=1;

                }

            }


        }
        return result;
    }
  public static int get_occure(int[] a)
    {
        int[] arr = a;
        int c = 1, maxcount = 1, maxvalue = 0;
        int result = 0;
        for (int i = 0; i < arr.Length; i++)
        {
            maxvalue = arr[i];
            for (int j = 0; j <arr.Length; j++)
            {

                if (maxvalue == arr[j] && j != i)
                {
                    c++;
                    if (c > maxcount)
                    {
                        maxcount = c;
                        result = arr[i];

                    }
                }
                else
                {
                    c=1;

                }

            }


        }
        return result;
    }
呆萌少年 2024-09-05 08:34:19

也许 O(n log n),但速度很快:

sort the array a[n]

// assuming n > 0
int iBest = -1;  // index of first number in most popular subset
int nBest = -1;  // popularity of most popular number
// for each subset of numbers
for(int i = 0; i < n; ){
  int ii = i; // ii = index of first number in subset
  int nn = 0; // nn = count of numbers in subset
  // for each number in subset, count it
  for (; i < n && a[i]==a[ii]; i++, nn++ ){}
  // if the subset has more numbers than the best so far
  // remember it as the new best
  if (nBest < nn){nBest = nn; iBest = ii;}
}

// print the most popular value and how popular it is
print a[iBest], nBest

Maybe O(n log n), but fast:

sort the array a[n]

// assuming n > 0
int iBest = -1;  // index of first number in most popular subset
int nBest = -1;  // popularity of most popular number
// for each subset of numbers
for(int i = 0; i < n; ){
  int ii = i; // ii = index of first number in subset
  int nn = 0; // nn = count of numbers in subset
  // for each number in subset, count it
  for (; i < n && a[i]==a[ii]; i++, nn++ ){}
  // if the subset has more numbers than the best so far
  // remember it as the new best
  if (nBest < nn){nBest = nn; iBest = ii;}
}

// print the most popular value and how popular it is
print a[iBest], nBest
各自安好 2024-09-05 08:34:19

linq 的另一个解决方案:

static int[] GetMostCommonIntegers(int[] nums)
{
    return nums
            .ToLookup(n => n)
            .ToLookup(l => l.Count(), l => l.Key)
            .OrderBy(l => l.Key)
            .Last() 
            .ToArray();
}   

此解决方案可以处理多个数字出现相同次数的情况:

[1,4,5,7,1] => [1]
[1,1,2,2,3,4,5] => [1,2]
[6,6,6,2,2,1] => [6]

Yet another solution with linq:

static int[] GetMostCommonIntegers(int[] nums)
{
    return nums
            .ToLookup(n => n)
            .ToLookup(l => l.Count(), l => l.Key)
            .OrderBy(l => l.Key)
            .Last() 
            .ToArray();
}   

This solution can handle case when several numbers have the same number of occurences:

[1,4,5,7,1] => [1]
[1,1,2,2,3,4,5] => [1,2]
[6,6,6,2,2,1] => [6]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文