Catalogue
169. Majority Element
Solution1. Hash Table
- Time : O(n), Space : O(n)
1
2
3
4
5
6
7
8class Solution(object):
def majorityElement(self, nums):
n = len(nums)
dic = collections.defaultdict(int)
for num in nums:
dic[num] += 1
if dic[num] > n/2:
return num
Solution2. Voting Algorithm
- Time : O(n), Space :O(1)
- Maintain a pair candidate, counter
- When a new element x comes in,
- if counter == 0, just set candidate = x, counter = 1
- else if x == candidate, counter ++ else counter –
1
2
3
4
5
6
7
8
9
10
11
12class Solution(object):
def majorityElement(self, nums):
candidate = None
counter = 0
for num in nums:
if counter == 0:
candidate = num
counter = 1
else:
counter += 1 if candidate == num else -1
return candidate
229. Majority Element II
Solution1. Hash table
Time : O(n), Space : O(n)1
2
3
4
5
6
7
8
9
10class Solution(object):
def majorityElement(self, nums):
n = len(nums)
dic = collections.defaultdict(int)
res = set()
for num in nums:
dic[num] += 1
if dic[num] > n / 3:
res.add(num)
return list(res)
Solution2. Voting Algorithm
- Time : O(n), Space : O(1)
1 | class Solution(object): |
Majority Element III
duplicates > [1/k], we need k-1 candidates, so the space complexity is O(k)
Majority Element IV
- what if the input in sorted, you wanna find the majority number appears n / 4 times!
277. Find the Celebrity
Solution1. Divede and Conquer O(nlogn)
1 | class Solution(object): |
Solution2. Voting O(n)
- Something like the Voting algorithm
1 | class Solution(object): |