首页 > 解决方案 > 用于查找数组中重复次数最多的 C# 函数

问题描述

您好我正在尝试为一个函数编写一个 C# (Visual Studio) 程序,该函数在数组中接受整数,并返回一个整数数组,其中包含输入数组中最常见的整数。

样品输入输出 -

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

我快到了,但没有得到预期的结果。以下是我编写的代码,我是初学者。

namespace StringCommonElements
{
    class Program
    {
        static void Main(string[] args)
        {
            // Compute frequencies for this data.
            string[] values = { "bird", "cat", "bird", "dog", "bird", "man", "frog", "cat" };
            // Get a list.
            List<string> valuesList = new List<string>(values);
            // Call our methods.
            var freqs = GetFrequencies(valuesList);
            DisplaySortedFrequencies(freqs);
        }
        static Dictionary<string, int> GetFrequencies(List<string> values)
        {
            var result = new Dictionary<string, int>();
            foreach (string value in values)
            {
                if (result.TryGetValue(value, out int count))
                {
                    // Increase existing value.
                    result[value] = count + 1;
                }
                else
                {
                    // New value, set to 1.
                    result.Add(value, 1);
                }
            }
            // Return the dictionary.
            return result;
        }
        static void DisplaySortedFrequencies(Dictionary<string, int> frequencies)
        {
            // Order pairs in dictionary from high to low frequency.
            var sorted = from pair in frequencies
                         orderby pair.Value descending
                         select pair;

            // Display all results in order.
            foreach (var pair in sorted)
            {
                Console.WriteLine($"{pair.Key} = {pair.Value}");
            }
        }

    }
}

标签: c#

解决方案


这是使用 Linq 执行此操作的方法。这将对数字进行分组并找到每个数字的计数,然后取出所有出现多次的数字。然后,如果结果为空,则返回原始数组,因为所有数字都是唯一的。

public int[] MostCommon(int[] numbers)
{
    var ans = numbers
        .GroupBy(x => x)            
        .Select(x => new {x.Key, x.Count}))
        .Where(x => x.Count > 1)
        .Select(x => x.Key)
        .ToArray();
    return ans.Length > 0 ? ans : numbers;
}

推荐阅读