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.
用dictionary来存储<数字,该数字出现次数> 当出现次数达到要求是,返回该数字即可。
public class Solution { public int MajorityElement(int[] nums) { Dictionary<int, int> dic = new Dictionary<int, int>(); for(int i = 0; i < nums.Count(); i++) { if(!dic.ContainsKey(nums[i])) { dic.Add(nums[i], 1); } else { dic[nums[i]]++; } if(dic[nums[i]] > nums.Count() / 2) { return nums[i]; } } return 0; } }