A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, these are arithmetic sequence:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not arithmetic.
1, 1, 2, 5, 7
一道中等难度的题目
题意是说能数组中含有多少连续的等差序列,最简单的方法是列出所有的序列,装入数组中,最后返回数组的长度,但这样时间极久。我们想,我们其实没必要每次都重复计算新的序列是不是等差序列,假设已经计算过A[1],A[2],A[3]为等差序列,那么在计算A[1],A[2],A[3],A[4]是否为等差序列的时候,只需要在之前计算的结果上,用A[4]-A[3]看看是否等于前面的等差dif,是则装入结果,否则continue。这样我们省去了重复计算的部分,但是仍然需要维持一个二维数组来记录已满足的等差序列,空间复杂度仍然是O(N^2),可以考虑,其实判断新添加的元素能否和过去的序列组成新的等差序列,只需要用一个pair结构,维持一个dif,和之前等差序列的最后一个元素index就行了,每次判断新元素是否合理的时候,只需要判断A[index+1]-A[index]==dif即可,如果满足,更新此pair,这样只需要O(N)的空间复杂度即可,代码如下:
0ms
int numberOfArithmeticSlices(vector<int>& A) {
if(A.size()<3)
return 0;
vector<pair<int,int>>work;
for(int i=0;i<A.size()-2;++i){
int dif=A[i+1]-A[i];
work.push_back({i+1,dif});
}
int res=0;
while(!work.empty()){
int k=0;
vector<pair<int,int>>next;
while(k<work.size()){
int pos=work[k].first;
int dif=work[k].second;
if(pos+1<A.size() && A[pos+1]-A[pos]==dif){
++res;
next.push_back({pos+1,dif});
}
++k;
}
swap(work,next);
}
return res;
}