169. Majority Element
#array #moores_voting_algorithm
Last updated
#array #moores_voting_algorithm
Last updated
class Solution {
public int majorityElement(int[] nums) {
// we count the votes
// number of votes will be > 0 only for the majority element
int count = 1, candidate = nums[0];
for (int i = 1; i < nums.length; ++i) {
if(nums[i] == candidate) {
count++;
} else {
// if the element is different consider it as vote againts
count--;
// if votes is 0 then replace the candiate
if(count == 0) {
candidate = nums[i];
count = 1;
}
}
}
return candidate;
}
}