Skip to content

Instantly share code, notes, and snippets.

@taravancil
Last active April 30, 2018 04:32
Show Gist options
  • Save taravancil/1a2e54e2e1d8ec59285d99938dbed65d to your computer and use it in GitHub Desktop.
Save taravancil/1a2e54e2e1d8ec59285d99938dbed65d to your computer and use it in GitHub Desktop.
Find the majority element in an array
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
@g10guang
Copy link

This algorithm only works when the amount of majority more than half length of array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment