Created
March 14, 2013 03:32
-
-
Save KodeSeeker/5158605 to your computer and use it in GitHub Desktop.
Finding the majority element in an array
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) { | |
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