CSharp · Console
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static int? GetMajorElement(int[] arr)
{
int? noMajorElement = null;
var dict = new Dictionary<int, int>();
// По сути HashMap: number -> кол-во вхождений в массив
foreach (var item in arr)
{
if (dict.ContainsKey(item))
{
dict[item]++;
}
else
{
dict[item] = 1;
}
}
// Находим такой элемент (если существует), ктр
// входит в массив больше чем [Размер массива / 2]
List<int> majorElements = dict
.Where(x => x.Value > (int)Math.Floor(arr.Length / 2.0))
.Select(x => x.Key)
.ToList();
return majorElements.Any() ? majorElements.First() : noMajorElement;
}
public static void Main()
{
Console.WriteLine("UniLecs");
int[] arr = new int[] { 1, 2, 3, 4, 1, 1, 1 };
int? result = GetMajorElement(arr);
Console.WriteLine(string.Format("Answer = {0}", result.HasValue ? result.ToString() : "No major element"));
}
}