LeetCode 229. Majority Element II
考点 | 难度 |
---|---|
Hash Map | Medium |
题目
Given an integer array of size n
, find all elements that appear more than ⌊ n/3 ⌋
times.
思路
Boyer-Moore Majority Vote algorithm, 因为题上问n/3,所以需要两个candidates。
答案
class Solution:
# @param {integer[]} nums
# @return {integer[]}
def majorityElement(self, nums):
if not nums:
return []
count1, count2, candidate1, candidate2 = 0, 0, 0, 1
for n in nums:
if n == candidate1:
count1 += 1
elif n == candidate2:
count2 += 1
elif count1 == 0:
candidate1, count1 = n, 1
elif count2 == 0:
candidate2, count2 = n, 1
else:
count1, count2 = count1 - 1, count2 - 1
return [n for n in (candidate1, candidate2)
if nums.count(n) > len(nums) // 3]