查找数组中最大值的出现

Finding Occurance of Max Value in Array

我正在尝试查找整数数组中最大值的出现次数。

例如

int[] ar = [3, 1, 2, 3];

此处,Max 3 重复两次,因此预期输出为 2

这行得通,我得到的计数是 2,因为最大值 3 在数组中出现了两次

var max = int.MinValue;
var occurrenceCount = 0;

foreach(var x in ar)
{
    if (x >= max) max = x;
}

foreach(var x in ar)
{
    if (x == max) occurrenceCount++;
}

Output: 2 //occurrenceCount

有了Linq就更简单了,

var occurrenceCount = ar.Count(x => x == ar.Max())

Output: 2 //occurrenceCount

现在没有 Linq,有没有任何简化或有效的方法来做到这一点?

至少,你可以合并前两个数组。我仍然会使用 Linq 解决方案。它更清楚。如果您真的想谈论性能,请先阅读 Which is faster?

所以这是一个 O(n) 的解决方案:

int[] ar = {3, 1, 2, 3, 3, 4, 4};
int max = ar[0];
var occurrenceCount = 1;

for(var i = 1; i < ar.Length; i++)
{
    if (ar[i] > max) {
	max = ar[i];
	occurrenceCount = 1;
    }
    else if (ar[i] == max) {
        occurrenceCount++;
    }
}

WriteLine(max);
WriteLine(occurrenceCount);

Try it online!

  • 请注意,您应该处理数组为空的情况。

我没有使用linq。我用了拉姆达:)

 int[] ar = new[] { 3, 1, 2, 3 };


        var result = ar.GroupBy(x => x) //values groups
        .Select(x => new
        {
            Number = x.Key,
            Count = x.Count()
        }).OrderByDescending(x => x.Count) //Short
        .FirstOrDefault(); //First Result


 result.Count // how many 

 result.Key   // max number

没有 Linq 也没有 Lamda

 int[] ar = new[] { 3, 1, 2, 3 };
            Array.Sort(ar);
            Array.Reverse(ar);
            var maxValue = ar[0];
            var occurrenceCount = 0;
            foreach (var item in ar)
            {
                if (item == maxValue)
                    occurrenceCount++;
            }

基于 Max 的 implementation 和 Enumerable 上的 GetCount,您可以通过在 Max 的 foreach 中添加一个测试来简单地因式分解,例如:

public static int CountMax(this IEnumerable<int> source)
{
    if (source == null)
    {
        throw new ArgumentException();
    }

    int value = 0;
    bool hasValue = false;
    int count = 0;

    foreach (int x in source)
    {
        if (hasValue)
        {
            if (x > value)
            {
                value = x;
                count = 1;
            }
            else if (x == value)
            {
                count++;
            }
        }
        else
        {
            value = x;
            count = 1;
            hasValue = true;
        }
    }
    if (hasValue)
    {
        return count;
    }

    throw new Exception("no elements");
}

很酷的部分是很容易让它更像 :

public static int CountMax<TSource>(this IEnumerable<TSource> source) where TSource : IComparable

您可以尝试更灵活的方法:

using System.Collections.Generic;

namespace ConsoleApp42
{
    class Program
    {
        static void Main (string[] args)
        {
            var array = new int[] { 1, 2, 3, 1, 1, 4, 4, 4, 4, 1, 1, 1 };
            //var array = new string[] { "a", "b", "a", "a" };

            var result = array.MaxCount ();
        }
    }

    public static class Extensions
    {
        public static (long count, T max) MaxCount<T> (this IEnumerable<T> source, IComparer<T> comparer = null)
        {
            if (comparer is null) comparer = Comparer<T>.Default;

            (long count, T max) result = (0, default (T));

            foreach (var element in source)
            {
                if (result.count == 0) // is first element?
                {
                    result.max = element;
                    result.count = 1;

                    continue;
                }

                int compareResult = comparer.Compare (element, result.max);

                if (compareResult == 0) // element == max
                {
                    result.count++;
                }
                else if (compareResult > 0) // element > max
                {
                    result.max = element;
                    result.count = 1;
                }
            }

            return result;
        }
    }
}
 int[] list = new int[] { 1, 1, 2, 3, 6, 7, 6, 6, 6, 8, 9 };
        Dictionary<int, int> occ = new Dictionary<int, int>();
        for (int i = 0; i < list.Length; i++)
        {
            var val = list[i];
            var count = 0;
            for (int j = 0; j < list.Length; j++)
            {
                if (val == list[j])
                {
                    count++;
                }
            }
            occ.TryAdd(val, count);
        }
        var maxCount = occ.Values.Max();
        var repNumber = occ.FirstOrDefault(x => x.Value == maxCount).Key;