如果[1,2,3,4,5,6]是一个等差数列,则
以A[2]结尾的等差数列 [1,2,3] 以A[3]结尾的等差数列 [1,2,3,4],[2,3,4] 以A[4]结尾的等差数列
[1,2,3,4,5],[2,3,4,5],[3,4,5]
以A[5]结尾的等差数列 [1,2,3,4,5,6],[2,3,4,5,6],[3,4,5,6],[4,5,6]
设f[i]
以A[i]
为结尾的等差数列的个数。
答案为f[]
数组的总和
class Solution {
public int numberOfArithmeticSlices(int[] A) {
int n = A.length;
if(n < 3)
return 0;
int []f = new int[n];
int res=0;
for(int i = 2;i < n;i++){
if(A[i]-A[i-1]==A[i-1]-A[i-2])
f[i]=f[i-1]+1;
res += f[i];
}
return res;
}
}
来源:CSDN
作者:Coldc0
链接:https://blog.csdn.net/qq_43118676/article/details/104784209