Last active
April 30, 2018 04:32
-
-
Save taravancil/1a2e54e2e1d8ec59285d99938dbed65d to your computer and use it in GitHub Desktop.
Find the majority element in an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_majority(A, k): | |
""" | |
Return the majority element in an array. O(n) time. | |
This is an implementation of Moore's voting algorithm. | |
""" | |
maj_index = 0 | |
count = 1 | |
for i in range (1, len(A-1)): | |
# If the current element is equal to the index of the majority element, increment count | |
if A[maj_index] == A[i]: | |
count += 1 | |
# Otherwise decrement count | |
else: | |
count -= 1 | |
# If the count is zero, it's not the max element, so set the majority index to the | |
# current index and increment the count | |
if count == 0: | |
maj_index = i | |
count = 1 | |
# Check that the number of times the elemnt occurs is actually a majority | |
if count > n/2: | |
return A[maj_index] | |
else: | |
return None | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This algorithm only works when the amount of majority more than half length of array.