forked from vJechsmayr/PythonAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0169_Majority_Element.py
More file actions
28 lines (24 loc) · 870 Bytes
/
Copy path0169_Majority_Element.py
File metadata and controls
28 lines (24 loc) · 870 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
# this class will give us a solution
class Solution:
# the function to find the majority element
def majorityElement(self, arr):
"""
finds the majority element in the arr
:param arr: List[int] a list with elements
:return: int , the majority element
"""
# a dictionary of numbers we have seen
seen_numbers = {}
if len(arr) <= 2:
return arr[0]
# goes through the list of numbers and count the appearance amount
for num in arr:
# adds it to the dictionary
if num not in seen_numbers:
seen_numbers[num] = 1
else:
if (seen_numbers[num] + 1) >= (len(arr) / 2):
return num
else:
# adds one to the counter
seen_numbers[num] += 1