Skip to content
Snippets Groups Projects

Majority Element

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    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));
            }
    
        }
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment