Skip to content

Instantly share code, notes, and snippets.

@clarkdo
Created January 30, 2018 08:28
Show Gist options
  • Save clarkdo/287da9e6814c37ec16a1c8e1a5000fc6 to your computer and use it in GitHub Desktop.
Save clarkdo/287da9e6814c37ec16a1c8e1a5000fc6 to your computer and use it in GitHub Desktop.
class Solution {
public int solution(int[] A) {
int length = A.length;
int leader = A[0];
int votes = 1;
//Boyer–Moore majority vote algorithm
for (int i = 1; i < length; i++) {
int digit = A[i];
votes += digit == leader ? 1 : -1;
if (votes == 0) {
leader = digit;
votes = 1;
}
}
votes = 0;
for (int i : A) {
if (i == leader) {
votes++;
}
}
if (votes <= length/2) return 0;
int count = 0;
int equiVotes = 0;
for (int i = 0; i < length; i++) {
int digit = A[i];
if (digit == leader) {
equiVotes++;
votes--;
}
if (equiVotes > (i+1)/2 && votes > (length - i -1)/2) {
count++;
}
}
return count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment