多数元素
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
这道题主体思想是哈希映射。python的字典就使用了hash的思想。直接贴代码。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
n = len(nums)
over = []
cnt = [0 for i in range(n)]
for i in range(len(nums)):
if nums[i] in over:
continue
else:
over.append(nums[i])
for i in range(len(nums)):
x = 0
cnt