// you can also use includes, for example:
// #include <algorithm>
int solution(const vector<int> &A) {
// write your code in C++98
//...record the count of current winner number, then
int winnerNumber;
int winnerNumberLeftCount = 0;
for(int i = 0; i < A.size(); ++i)
{
if(winnerNumberLeftCount == 0)
{
winnerNumber = A[i];
winnerNumberLeftCount++;
}
else
{
if(winnerNumber == A[i]) winnerNumberLeftCount++;
else winnerNumberLeftCount--;
}
}
//...enumetate the array and count the occurence of this winner number,
if(winnerNumberLeftCount <= 0) return -1;
int winnerNumberRealCnt = 0;
int index;
for(int i = 0; i < A.size(); ++i)
{
if(A[i] == winnerNumber)
{
winnerNumberRealCnt++;
index = i;
}
}
//...if the last winner number is not the dominator then return -1
if(winnerNumberRealCnt <= (int)A.size()/2) return -1;
else return index;
}
[codility]Dominator
最新推荐文章于 2018-04-22 19:15:58 发布