leetcode-169 求众数
leetcode-169 求众数
题目描述:
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。你可以假设数组是非空的,并且给定的数组总是存在众数
class Solution:
def majorityElement(self, nums: List[int]) -> int:
numsdic = dict()
for v in nums:
numsdic.setdefault(v,0)
numsdic[v] += 1
for k,v in numsdic.items():
if v > len(nums)//2:
return k
class Solution:
def majorityElement(self, nums: List[int]) -> int:
major = count = 0
for i in nums:
if count == 0:
major = i
count = 1
else:
count += 1 if major == i else -1
return major