题目链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/
难度:简单
描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
题解
from collections import defaultdictclass Solution:def majorityElement(self, nums: List[int]) -> int:n = len(nums)m = defaultdict(int)for i in nums:m[i] += 1if m[i] > n // 2:return ireturn -1
