public class Solution { public int MajorityElement(int[] nums) { Dictionary<int, int> dic = new Dictionary<int, int>(); var len = nums.Length; for (int i = 0; i < len; i++) { if (!dic.ContainsKey(nums[i])) { dic.Add(nums[i], 1); } else { dic[nums[i]]++; } } var result = 0; foreach (var d in dic) { if (d.Value > len / 2) { result = d.Key; break; } } return result; } }
https://leetcode.com/problems/majority-element/#/description
补充一个python的实现:
1 class Solution: 2 def majorityElement(self, nums: 'List[int]') -> int: 3 dic = {} 4 length = len(nums) 5 for n in nums: 6 if n not in dic: 7 dic[n] = 1 8 else: 9 dic[n] += 1 10 if dic[n] > length // 2: 11 return n