Problem link is here:Codility
Although the function below got 100 out of 100.
I think it can be optimized somehow.
// you can also use includes, for example:
// #include <algorithm>
int solution(const vector<int> &A)
{
// write your code in C++98
if(A.empty())
return -1;
int candidate = -1;
int index = -1;
int size = 0;
int counter = 0;
for(unsigned int i = 0; i < A.size(); i++)
{
if(0 == size)
{
candidate = A[i];
index = i;
size++;
}
else
{
if(candidate == A[i])
size++;
else
size--;
}
}
if(size == 0)
return -1;
for(unsigned int i = 0; i < A.size(); i++)
{
if(candidate == A[i])
counter++;
}
if( (float)counter / A.size() > 0.5f)
return index;
else
return -1;
}