Majority Element
The snippet can be accessed without any authentication.
Authored by
Kiryuu Sakuya
Program.cs 1.16 KiB
using System;
using System.Collections.Generic;
namespace test
{
class Program
{
public static int MajorityElement(int[] nums)
{
Dictionary<int, int> count = new Dictionary<int, int>();
// Iterate your array, add a key the dictionary for each unique elem
// increment the value each time that element is repeated.
foreach (int num in nums)
{
if (!count.ContainsKey(num))
count.Add(num, 1);
else
count[num]++;
}
// Walk the dictionary keys, and return the elem with the highest value.
int high = 0;
int highelem = 0;
foreach (KeyValuePair<int, int> nep in count)
{
if (nep.Value > high)
{
high = nep.Value;
highelem = nep.Key;
}
}
return highelem;
}
public static void Main(string[] args)
{
int[] a = { 2, 2, 1, 1, 1, 2, 2 };
Console.WriteLine(MajorityElement(a));
}
}
}
Please register or sign in to comment