给定一个大小为n
的整数数组,找出其中所有出现超过⌊ n/3 ⌋
次的元素。
进阶:尝试设计时间复杂度为O(n)
、空间复杂度为O(1)
的算法解决此问题。
示例 1:
输入:[3,2,3]
输出:[3]
示例 2:
输入:nums = [1]
输出:[1]
示例 3:
输入:[1,1,1,3,3,2,2,2]
输出:[1,2]
提示:
1 <= nums.length <= 5*10^4
-10^9 <= nums[i] <= 10^9
1.暴力字典
Python解答:
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
adic = {}
for num in nums:
if num not in adic.keys():
adic[num] = 1
else:
adic[num] += 1
return [key for key, value in adic.items() if value > len(nums)//3]
2.摩尔投票
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
value = [None, None]
count = [0, 0]
i = 0
while i < len(nums):
if nums[i] == value[0]:
count[0] += 1
elif nums[i] == value[1]:
count[1] += 1
elif count[0] == 0:
value[0] = nums[i]
count[0] = 1
elif count[1] == 0:
value[1] = nums[i]
count[1] = 1
else:
count[0] -= 1
count[1] -= 1
i += 1
t = [0, 0]
for i in range(len(nums)):
if nums[i] == value[0]:
t[0] += 1
if nums[i] == value[1]:
t[1] += 1
return [value[i] for i in range(2) if t[i] > len(nums)//3]
留言