-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy path169_majority_element.py
More file actions
58 lines (44 loc) · 1.02 KB
/
169_majority_element.py
File metadata and controls
58 lines (44 loc) · 1.02 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
49
50
51
52
53
54
55
56
57
58
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
ans = None
cnt = 0
for num in nums:
if cnt == 0:
ans, cnt = num, 1
elif ans == num:
cnt += 1
else:
cnt -= 1
return ans
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
nums.sort()
return nums[len(nums) // 2]
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
NOT_FOUND = 0
if not nums:
return NOT_FOUND
freq = {}
for a in nums:
freq[a] = freq.get(a, 0) + 1
for a, cnt in freq.items():
if cnt > len(nums) // 2:
return a
return NOT_FOUND