1、题目描述
给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。
说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
示例 1:
输入: [3,2,3] 输出: [3]
示例 2:
输入: [1,1,1,3,3,2,2,2] 输出: [1,2]
2、题解
2.1、解法一
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n = len(nums)
m = n//3
dic = {}
i = 0
while i <n:
k = nums[i]
if k not in dic:
dic[k] = 1
else:
print(k)
dic[k] = dic[k] +1
i += 1
print(m)
print(dic)
return [i for i in dic if dic[i] >m]
2.2、解法二
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n = len(nums)
m = n//3
nums.sort()
i = 0
ret = []
while i <n:
tmp = nums[i]
count = 0
while i < n and nums[i] == tmp:
count += 1
i += 1
if count > m:
ret.append(tmp)
if count == 0:
i = i+1
return ret