Solution with time complexity O(N) and space complexity O(1)


#1

int Solution::majorityElement(const vector &A) {
int me=-1;
int n=A.size();
int count=0;
for(int i=0;i<n;i++)
{
if(count==0)
{
me=A[i];
count++;
}
else if(me!=A[i])
{
count–;
if(count==0)
me=-1;
}
else if(me==A[i])
count++;
}
return me;
}