35 lines
733 B
C++
35 lines
733 B
C++
/*
|
|
Majority Element (https://www.interviewbit.com/problems/majority-element/)
|
|
|
|
Asked in:
|
|
Microsoft
|
|
Yahoo
|
|
Google
|
|
Amazon
|
|
|
|
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.
|
|
|
|
*/
|
|
int Solution::majorityElement(const vector<int> &A) {
|
|
int c =0;
|
|
int e =0;
|
|
for (int a : A){
|
|
if (c == 0){
|
|
e = a;
|
|
c++;
|
|
} else if ( e != a ){
|
|
c--;
|
|
} else {
|
|
c++;
|
|
}
|
|
}
|
|
return e;
|
|
}
|