LeetCode_169.多数元素

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [3,2,3]
输出: 3

示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

C#代码

public class Solution {
    public int MajorityElement(int[] nums) {
        Dictionary<int,int> dic = new Dictionary<int,int>();
        for(int i = 0; i < nums.Length; i++){
            if(dic.ContainsKey(nums[i]))dic[nums[i]] += 1;
            else dic.Add(nums[i], 1);    
            if(dic[nums[i]] > nums.Length / 2) return nums[i];
        }
        return 0;
    }
}
原文地址:https://www.cnblogs.com/fuxuyang/p/14242768.html