Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 18, 2016 07:06
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 jianminchen/c6f01498a6de4ca2df3d813b375a3d6d to your computer and use it in GitHub Desktop.
Save jianminchen/c6f01498a6de4ca2df3d813b375a3d6d to your computer and use it in GitHub Desktop.
Majority - facebook code lab - pass all test cases
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