-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path229.py
More file actions
62 lines (51 loc) · 1.4 KB
/
229.py
File metadata and controls
62 lines (51 loc) · 1.4 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
59
60
61
62
from collections import Counter
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# solution1
# if not nums:
# return []
# n = int(len(nums)/3)+1
# nums = Counter(nums)
# ans = list()
# for k, v in nums.items():
# if v >= n:
# ans.append(k)
#
# return ans
# solution2
if not nums:
return []
candidate1, candidate2, count1, count2 = 0, 0, 0, 0
ans = list()
for num in nums:
if num == candidate1:
count1 += 1
elif num == candidate2:
count2 += 1
elif count1 == 0:
candidate1 = num
count1 += 1
elif count2 == 0:
candidate2 = num
count2 += 1
else:
count1 -= 1
count2 -= 1
count1, count2 = 0, 0
for num in nums:
if num == candidate1:
count1 += 1
elif num == candidate2:
count2 += 1
if count1 > len(nums) / 3:
ans.append(candidate1)
if count2 > len(nums) / 3:
ans.append(candidate2)
return ans
nums = [1, 1, 1, 1, 2, 2, 3, 3]
test = Solution()
print(test.majorityElement(nums))