Leetcode 169.多数元素
1 题目描述(Leetcode题目链接)
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。你可以假设数组是非空的,并且给定的数组总是存在多数元素。
输入: [3,2,3]
输出: 3
输入: [2,2,1,1,1,2,2]
输出: 2
2 题解
排序后中间的数一定是最多的元素。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
return sorted(nums)[len(nums)//2]
摩尔投票法,记录一个数和其出现次数,遇到相同的加1,不同的减1,减到0时更新为新的数。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
retv = nums[0]
cnt = 1
for i in range(1, len(nums)):
if nums[i] == retv:
cnt += 1
else:
cnt -= 1
if cnt == 0:
retv = nums[i+1]
return retv