Skip to content

Instantly share code, notes, and snippets.

@KodeSeeker
Created March 14, 2013 03:32
Show Gist options
  • Save KodeSeeker/5158605 to your computer and use it in GitHub Desktop.
Save KodeSeeker/5158605 to your computer and use it in GitHub Desktop.
Finding the majority element in an array
public class MajorityElement {
public static void main(String[] args) {
int[] list = new int[] {1, 2, 3, 4, 2, 3, 4, 2, 3, 2, 1, 2, 3, 4, 2, 2, 2};
int count = 1;
int majorityElement = list[0];
for(int index = 1; index < list.length; index++) {
if(majorityElement != list[index]) {
if(count == 0) {
majorityElement = list[index];
count++;
}
else
count--;
}
else
count++;
}
System.out.println("Majority Element: " + majorityElement);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment