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 zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.
A slice (P, Q) of array A is called arithmetic if the sequence:
A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.
The function should return the number of arithmetic slices in the array A.
Example:
A = [1, 2, 3, 4]
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
思路:題目很冗長,實際上就是找有幾個等差數(shù)列(長度大于3的).i作為序列頭,從0開始到N-3遍歷數(shù)組,首先找一個最短的等差序列(長度為3),找到后算出間距dist,再以j為序列尾,從i+3開始到N向后擴張,看等差序列是否還存在后續(xù).只要找到一個間距不等于dist,表明在這里斷開,退出內(nèi)層j循環(huán),序列頭后移一位.如此往復(fù)
int numberOfArithmeticSlices(vector<int>& A) {
int N = A.size();
int count = 0;
if (N < 3) return 0; //特殊情況處理
for (int i = 0; i < N-2; i++) { //遍歷0到N-3的位置
if (A[i+1] - A[i] != A[i+2] - A[i+1]) continue; //A[i,i+1,i+2]不滿足等差數(shù)列,直接跳過本次循環(huán)
int dist = A[i+1] - A[i]; //等差間距distance
count++; //找到一個等差
for (int j = i+3; j < N; j++) { //j從i+2之后找,看等差序列是否還存在后續(xù)
if (A[j] - A[j-1] != dist) break; //只要發(fā)現(xiàn)一個不等的,立即退出循環(huán)
count++;
}
}
return count;
}