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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
这题要求寻找一个数组中出现次数最多的元素,并且该元素的出现次数一定大于 ⌊ n/2 ⌋
次。因此建立一个字典,储存每个元素出现的次数即可,若次数大于 ⌊ n/2 ⌋
,就输出该元素。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
dic = {}
l = len(nums)
for i in range(l):
if nums[i] not in dic.keys():
dic[nums[i]] = 1
else:
dic[nums[i]] += 1
if dic[nums[i]] >= (l+1)//2:
return nums[i]