[LeetCode] Majority Element solution

来源:互联网 发布:铃声mac版 编辑:程序博客网 时间:2024/06/04 20:02

Given an array of size n find the majority element.

The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.


ideas

1. use hashtable to save the number of the array,

2. then check the number of array elements.

3. If it is more than ⌊ n/2 ⌋ times, output this array element.


public class Solution {    public int MajorityElement(int[] nums) {        Dictionary <int, int> myDic =  new Dictionary<int, int>();                int length = nums.Length;        int result = 0;        for(int i = 0; i < length; i++)        {            if(myDic.ContainsKey(nums[i]))            {                myDic[nums[i]]++;            }            else            {                myDic.Add(nums[i], 0);            }        }                for(int i = 0; i < length; i++)        {            if(myDic[nums[i]] >= length/2)                result = nums[i];        }                return result;            }}





0 0
原创粉丝点击