2021/winter interview training for facebook/google
This commit is contained in:
34
puzzles/training/majority_element.cpp
Normal file
34
puzzles/training/majority_element.cpp
Normal file
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user