You are given an integer array nums of size n, find all elements that appear more than ⌊ n/3 ⌋ times. You can return the result in any order.
Example 1:
Input: nums = [5,2,3,2,2,2,2,5,5,5]
Output: [2,5]Example 2:
Input: nums = [4,4,4,4,4]
Output: [4]Example 3:
Input: nums = [1,2,3]
Output: []Constraints:
1 <= nums.length <= 50,000.-1,000,000,000 <= nums[i] <= 1,000,000,000Follow up: Could you solve the problem in linear time and in O(1) space?
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
res = set()
for num in nums:
count = sum(1 for i in nums if i == num)
if count > len(nums) // 3:
res.add(num)
return list(res)class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
nums.sort()
res, n = [], len(nums)
i = 0
while i < n:
j = i + 1
while j < n and nums[i] == nums[j]:
j += 1
if (j - i) > n // 3:
res.append(nums[i])
i = j
return resclass Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
count = Counter(nums)
res = []
for key in count:
if count[key] > len(nums) // 3:
res.append(key)
return resclass Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
n = len(nums)
num1 = num2 = -1
cnt1 = cnt2 = 0
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
cnt2 += 1
elif cnt1 == 0:
cnt1 = 1
num1 = num
elif cnt2 == 0:
cnt2 = 1
num2 = num
else:
cnt1 -= 1
cnt2 -= 1
cnt1 = cnt2 = 0
for num in nums:
if num == num1:
cnt1 += 1
elif num == num2:
cnt2 += 1
res = []
if cnt1 > n // 3:
res.append(num1)
if cnt2 > n // 3:
res.append(num2)
return resclass Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
count = defaultdict(int)
for num in nums:
count[num] += 1
if len(count) <= 2:
continue
new_count = defaultdict(int)
for num, c in count.items():
if c > 1:
new_count[num] = c - 1
count = new_count
res = []
for num in count:
if nums.count(num) > len(nums) // 3:
res.append(num)
return res