В этом примере мы изучим различные способы поиска наиболее частого элемента в массиве в C#.
Использование Hashtable:
Вы можете использовать Hashtable, чтобы найти наиболее частый элемент в массиве.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Using_Hashtable
{
class Program
{
static void MaxOccurrence(int[] array, Hashtable hs)
{
int mostCommom = array[0];
int occurences = 0;
foreach (int num in array)
{
if (!hs.ContainsKey(num))
{
hs.Add(num, 1);
}
else
{
int tempOccurences = (int)hs[num];
tempOccurences++;
hs.Remove(num);
hs.Add(num, tempOccurences);
if (occurences < tempOccurences)
{
occurences = tempOccurences;
mostCommom = num;
}
}
}
Console.WriteLine("Наиболее часто встречающееся число: " + mostCommom + " и оно повторяется " + occurences + " раз");
}
public static void Main(string[] args)
{
int[] array = new int[20] { 3, 6, 8, 5, 3, 5, 7, 6, 4, 3, 2, 3, 5, 7, 6, 4, 3, 4, 5, 7 };
Hashtable hs = new Hashtable();
MaxOccurrence(array, hs);
Console.ReadKey();
}
}
}
Вывод:
Наиболее часто встречающееся число: 3 и оно повторяется 5 раз
