// 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
最新推荐文章于 2019-06-23 20:01:06 发布
本文介绍了一种通过双向遍历数组并比较元素绝对值的方法来确定不同绝对值元素的数量。此算法使用了从两端开始遍历的策略,并利用`llabs`函数获取长整型数值的绝对值,避免了溢出问题。

279

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



