Skip to content

Instantly share code, notes, and snippets.

@igalata
Created September 6, 2017 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igalata/77556d2b96a87a4ca2ad8452eaa698b3 to your computer and use it in GitHub Desktop.
Save igalata/77556d2b96a87a4ca2ad8452eaa698b3 to your computer and use it in GitHub Desktop.
public class MajorityElement {
public static void main(String[] args) {
System.out.println(findMajority(new int[]{3, 4, 5, 3, 5, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5, 5, 5}));
}
public static int findMajority(int[] array) {
int candidate = findCandidate(array);
return validate(array, candidate) ? candidate : -1;
}
private static int findCandidate(int[] array) {
if (array == null) return -1;
int counter = 0;
int candidate = 0;
for (int number : array) {
if (counter == 0) {
candidate = number;
}
if (candidate == number) {
++counter;
} else {
--counter;
}
}
return candidate;
}
private static boolean validate(int[] array, int candidate) {
int counter = 0;
for (int number : array) {
if (number == candidate) {
counter++;
}
}
return counter > array.length / 2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment