-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmajority-element.py
52 lines (40 loc) · 1.04 KB
/
majority-element.py
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
49
50
51
52
# Time: O(n)
# Space: O(1)
import collections
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def boyer_moore_majority_vote():
result, cnt = None, 0
for x in nums:
if not cnt:
result = x
if x == result:
cnt += 1
else:
cnt -= 1
return result
return boyer_moore_majority_vote()
# Time: O(n)
# Space: O(n)
import collections
class Solution2(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return collections.Counter(nums).most_common(1)[0][0]
# Time: O(nlogn)
# Space: O(n)
import collections
class Solution3(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sorted(collections.Counter(nums).items(), key=lambda a: a[1], reverse=True)[0][0]