題目:
給定一個大小為 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