Finding the majority element
only for case where majority has more than n/2 occurrences
Algorithm
// we count the votes
// number of votes will be > 0 only for the majority element
int candidate = -1, votes = 0;
for (int i = 0; i < nums.length; ++i) {
// if votes is 0 then replace the candiate
if(votes == 0) {
candidate = nums[i];
}
// if the element is different consider it as vote againts
votes+= (candidate == nums[i]) ? +1 : -1;
} Complexity
Reference
Last updated