Find Majority Element from an array
Mar 19, 2021
Given an array of size n
, find the majority element. The majority element is the element that appears more than floor(n/2)
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example :
Input : [2, 1, 2]
Return : 2 which occurs 2 times which is greater than 3/2.
public class Solution {
// DO NOT MODIFY THE LIST. IT IS READ ONLY
public int majorityElement(final List<Integer> A) {
int ans = A.get(0);
int counter = 1;
for(int i=1; i<A.size(); i++){
if(counter ==0){
ans = A.get(i);
counter++;
continue;
}
if(ans == A.get(i)){
counter++;
}else{
counter — ;
}
}
return ans;
}
}