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.
思路:题目很冗长,实际上就是找有几个等差数列(长度大于3的).i作为序列头,从0开始到N-3遍历数组,首先找一个最短的等差序列(长度为3),找到后算出间距dist,再以j为序列尾,从i+3开始到N向后扩张,看等差序列是否还存在后续.只要找到一个间距不等于dist,表明在这里断开,退出内层j循环,序列头后移一位.如此往复
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]不满足等差数列,直接跳过本次循环
int dist = A[i+1] - A[i]; //等差间距distance
count++; //找到一个等差
for (int j = i+3; j < N; j++) { //j从i+2之后找,看等差序列是否还存在后续
if (A[j] - A[j-1] != dist) break; //只要发现一个不等的,立即退出循环
count++;
}
}
return count;
}
网友评论