// 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 发布
本文介绍了一种寻找数组中主导元素的方法,主导元素是指出现次数超过数组长度一半的元素。通过遍历数组并使用计数的方式记录潜在主导元素,再验证该元素是否真正为主导元素。

354

被折叠的 条评论
为什么被折叠?



