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:
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的等差子数组个数;
乍一看用dp找不到递推,进一步分析我们只要知道一个等差子数组的长度,就能知道这个长度中可以截取出多少个符合条件的数组;
对于一个长度为n的等差数组有:
1个n;
2个n-1;
3个n-2;
…
n-2个3;
所以:
num(len)=1+2+3+...+n−2=(n−1)∗(n−2)2
n
u
m
(
l
e
n
)
=
1
+
2
+
3
+
.
.
.
+
n
−
2
=
(
n
−
1
)
∗
(
n
−
2
)
2
遍历一次数组,每次找等差最长数组,然后增大结果。
class Solution {
public int numberOfArithmeticSlices(int[] a) {
int res = 0;
for(int i = 0;i<a.length-2;i++){
int len = 2;
int d = a[i+1] - a[i];
i++;
while(i+1<a.length && a[i+1]-a[i]==d){
i++;
len++;
}
//Error!!!
i--;
res+= (len-2)*(len-1)/2;
}
return res;
}
}
注意: