// you can also use includes, for example:
// #include <algorithm>
int solution(const vector<int> &A) {
// write your code in C++98
//...traverse the array from both direction, and move according to the
//absolute value
int result = 0;
long long prevAbsoluteValue = -1;
for(int i = 0, j = A.size()-1; i <= j; )
{
long long absValueLeft = A[i];
//we need use llabs to get the absolute value of long long instead of abs
//to avoid overflow
absValueLeft = llabs(absValueLeft);
long long absValueRight = A[j];
absValueRight = llabs(absValueRight);
long long absBiggerNumber = max(absValueLeft, absValueRight);
if(absValueLeft > absValueRight) i++;
else j--;
if(prevAbsoluteValue != absBiggerNumber) result++;
prevAbsoluteValue = absBiggerNumber;
}
//...return result
return result;
}
[codility]Abs-distinct
最新推荐文章于 2018-04-22 15:57:00 发布