-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq_169_majority_element.py
More file actions
48 lines (42 loc) · 1.42 KB
/
q_169_majority_element.py
File metadata and controls
48 lines (42 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
##################################################
# Solution 3, moore voting algo
# candidate = nums[0]
# vote = 1
# for n in nums:
# if n == candidate:
# vote += 1
# else:
# vote -= 1
# if vote == 0:
# candidate = n
# vote = 1
# return candidate
##################################################
##################################################
# Solution 2, use sort first, time O(n log n), space O(1)
# nums.sort()
# n_maj = nums[len(nums)//2]
# return n_maj
##################################################
##################################################
# Solution 1, use dict, time O(n), space O(n)
count = {}
n_maj = nums[0]
# The threshold is KNOWN from problem description
freq_threshold = len(nums) // 2
for n in nums:
if n in count:
count[n] += 1
if count[n] > freq_threshold:
n_maj = n
break
else:
count[n] = 1
return n_maj
##################################################