- Notifications
You must be signed in to change notification settings - Fork 152
/
Copy pathmajority_element.py
28 lines (23 loc) · 777 Bytes
/
majority_element.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
# Problem: A majority element in an array A[] of
# size n is an element that appears more than n/2
# times. Find the majority element in the given array.
# Returns the elements whose frequency is more than n/2
deffindMajorityElement(elements, N, found=False):
keys= [int(i) foriinelements.keys()]
foriinkeys:
ifelements[i] >N//2:
found=True
print(i)
ifnotfound:
print("Majority element not found")
# Creates a hash of frequency of numbers
defmapFrequency(arr):
FREQUENCY= {}
foriinarr:
ifiinFREQUENCY.keys():
FREQUENCY[i] +=1
else:
FREQUENCY[i] =0
returnfindMajorityElement(FREQUENCY, len(arr))
arr= [1, 2, 4, 4, 4, 4, 4]
mapFrequency(arr)