题目:
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
思路:
使用哈希非常方便
程序:
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
length = len(nums)
if length <= 0:
return 0
if length == 1:
return nums[0]
my_hashMap = {}
for index in nums:
if index in my_hashMap:
my_hashMap[index] += 1
else:
my_hashMap[index] = 1
if my_hashMap[index] > len(nums) // 2:
return index