// you can also use includes, for example:
// #include <algorithm>
int getLeaderIndex(const vector<int> &A)
{
//...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;
}
int solution(vector<int> &A) {
// write your code in C++98
//...because equi_leader is both side arrays' leader, so it must also be
//leader of the whole array, so find out it first
int leaderIndex = getLeaderIndex(A);
if(leaderIndex == -1) return 0;
//...record the total count of leader number
int leaderNumber = A[leaderIndex];
int leaderNumTotalCnt = 0;
for(int i = 0; i < A.size(); ++i)
if(A[i] == leaderNumber) leaderNumTotalCnt++;
//...enumerate the whole array and keep records of the leader number's count in left side
// of the array, in the meantime check if current enumerated index can be the divider of equi_leader
int result = 0;
int leaderNumLeftCnt = 0;
for(int i = 0; i < A.size(); ++i)
{
if(A[i] == leaderNumber) leaderNumLeftCnt++;
//check
if(leaderNumLeftCnt > (i+1)/2 && (leaderNumTotalCnt-leaderNumLeftCnt) > (A.size()-i-1)/2)
result++;
}
//...return result
return result;
}
[codility]Equi-leader
最新推荐文章于 2018-04-22 19:15:58 发布