Created
September 6, 2017 13:58
-
-
Save igalata/77556d2b96a87a4ca2ad8452eaa698b3 to your computer and use it in GitHub Desktop.
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
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