728x90
https://leetcode.com/problems/majority-element-ii/description/
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
count = defaultdict(int)
for n in nums:
count[n] += 1
if len(count) <= 2:
continue
new_count = defaultdict(int)
for n, c in count.items():
if c > 1:
new_count[n] = c - 1
count = new_count
res = []
for n in count:
if nums.count(n) > len(nums) // 3:
res.append(n)
return res
we cannot have more than 2 answer since we are trying to find numbers that occur more than n / 3.
in hashmap we keep put numbers and count occurence.
when we have 3rd entry we decrement by 1 and remove if occurence become zero.
and later on check the numbers that are still in hashmap.
728x90
'Algorithm > NeetCode' 카테고리의 다른 글
Design a Food Rating System (0) | 2024.11.21 |
---|---|
Sum of Absolute Differences in a Sorted Array (0) | 2024.11.20 |
Champagne Tower (0) | 2024.11.18 |
Minimum Penalty for a Shop (0) | 2024.11.17 |
Design Underground System (0) | 2024.11.15 |