-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path229_MajorityElementII.py
More file actions
44 lines (43 loc) · 1.21 KB
/
229_MajorityElementII.py
File metadata and controls
44 lines (43 loc) · 1.21 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
class Solution:
# @param {integer[]} nums
# @return {integer[]}
def majorityElement(self, nums):
if not nums:
return []
candidate1 = None
candidate2 = None
count1 = 0
count2 = 0
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
result = []
threshold = len(nums) // 3
total1 = 0
total2 = 0
for idx in range(len(nums) - 1, -1, -1):
if nums[idx] == candidate1:
total1 += 1
continue
elif nums[idx] == candidate2:
total2 += 1
continue
if total1 > threshold:
result.append(candidate1)
if total2 > threshold:
result.append(candidate2)
return result
if __name__ == "__main__":
sol = Solution()
print sol.majorityElement([4, 2, 1, 1]) == [1]