-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfind_majority_element.py
More file actions
39 lines (33 loc) · 1006 Bytes
/
find_majority_element.py
File metadata and controls
39 lines (33 loc) · 1006 Bytes
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
"""
Given a sequence of elements a_1, a_2, ... , a_n, you would like to check whether
it contains an element (majority element) that appears more than n/2 times.
"""
def find_majority_element(values):
"""
Returns the majority element or None if no such element found
"""
def find_candidate():
candidate_index = 0
count = 1
for index in range(0, len(values)):
if values[candidate_index] == values[index]:
count += 1
else:
count -= 1
if count == 0:
candidate_index = index
count = 1
return values[candidate_index]
def is_majority(candidate):
count = 0
for value in values:
if value == candidate:
count += 1
return count > len(values) // 2
if not values:
return None
candidate = find_candidate()
if is_majority(candidate):
return candidate
else:
return None