-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathp17_10.py
39 lines (29 loc) · 845 Bytes
/
p17_10.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
from typing import List
# Method: If there is a majority element, it's going to have enough buget to displace all others
# Time: O(n)
# Space: O(1)
def majority_elem(arr):
candidate = maj_elem(arr)
return candidate if is_majority(candidate, arr) else -1
def is_majority(x: int, arr: List[int]) -> bool:
count = 0
for elem in arr:
count += elem == x
print(f"Count is {count}")
return count > len(arr) / 2
def maj_elem(arr: List[int]) -> int:
elem_now = arr[1]
count = 1
for i in range(1, len(arr)):
x = arr[i]
if x == elem_now:
count += 1
else:
count -= 1
if count < 1:
elem_now = x
count = 1
return elem_now
if __name__ == "__main__":
posib = [4, 4, 4, 4, 5, 5, 5, 5, 5]
print(majority_elem(posib))