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.源码:
class Solution {
public:
int numberOfArithmeticSlices(vector& num) {
int size = num.size();
if (size < 3)return 0;
vectorre(size,0);
for (int i = 2; i < size; i++){
int diff = num[i] - num[i - 1];
int k = i-1;
while (k>=1&&num[k]-num[k-1]==diff){
diff = num[k] - num[k - 1];
k--;
}
int start = k;
int end = i;
if (end - start + 1 < 3)re[i] = re[i-1];
else if (end - start + 1 == 3)re[i] = re[i-1]+1;
else{//连续的长度大于或等于4
int s1 = end - start + 1;
int s2 = end - start;
int base = 0;
int total1 = 0;
for (int j = 3; j <= s1; j++){//连续s1个等差数能够成的arithmetic slices的个数
total1 =total1+ (++base);
}
int total2 = 0;
base = 0;
for (int j = 3; j <= s2; j++){//连续s2个等差数能够成的arithmetic slices的个数
total2 = total2 + (++base);
}
re[i] = re[i - 1] + total1 - total2;
}
}
return re[size-1];
}
};
re[i]表示从下标0开始到下标i截止的字符串的连续等差数列的个数!!!!
后来在讨论区里看到另一种AC方法:
class Solution {
public:
int numberOfArithmeticSlices(vector& A) {
int n = A.size();
if (n < 3) return 0;
vector dp(n, 0); // dp[i] means the number of arithmetic slices ending with A[i]
if (A[2]-A[1] == A[1]-A[0]) dp[2] = 1; // if the first three numbers are arithmetic or not
int result = dp[2];
for (int i = 3; i < n; ++i) {
if (A[i]-A[i-1] == A[i-1]-A[i-2])
dp[i] = dp[i-1] + 1;
result += dp[i]; // accumulate all valid slices
}
return result;
}
};
其实这个题的抽象是:
对于一连串数num={1,3,5,7,9},一共5个数,假设我们知道这七个数之间是一个连续的等差数列,那么假如我们定义的等差数理的最少个
数是3,那么它一共有多少个连续长度>=3构成的等差序列,注意这里是连续的!!!
个数是3的时候:1,3,5;3,5,7;5,7,9;
个数是4个的时候:1,3,5,7;3,5,7,9;
个数是5个的时候:1,3,5,7,9;
一般的求连续s2个中含有个数大于或等于3个连续的等差数列的做法是:
int total2 = 0;
base = 0;
for (int j = 3; j <= s2; j++){ //连续s2个等差数能够成的arithmetic slices的个数
total2 = total2 + (++base);
}
re[i] = re[i - 1] + total1 - total2;