Created
July 18, 2016 07:06
-
-
Save jianminchen/c6f01498a6de4ca2df3d813b375a3d6d to your computer and use it in GitHub Desktop.
Majority - facebook code lab - pass all test cases
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 Solution { | |
public int majorityElement(final List<Integer> a) { | |
int len = a.size(); | |
int count = 1; | |
int majority = a.get(0).intValue(); | |
for(int i=1; i< a.size(); i++) | |
{ | |
int cur = a.get(i).intValue(); | |
// add new, delete | |
boolean setNewElement = count == 0; | |
boolean removeCurElement = count == 1 && (cur != majority); | |
// just update the count | |
boolean addOneMore = count >= 1 && cur == majority; // bug001 - >=,not > | |
boolean decrementOne = count > 1 && (cur != majority); | |
// set a new element to count | |
if(setNewElement) | |
{ | |
majority = cur; | |
count = 1; | |
} | |
else if(removeCurElement) | |
count = 0; | |
else if(addOneMore) | |
count ++; | |
else if(decrementOne) // | |
count --; | |
} | |
return majority; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment