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.
具体题目要求:点击打开链接
思路:
查看三个条件:1.数组A长度是否大于3;
2.每个连续长度大于3的部分是否相邻两数相减之差相同;
3.对于每个连续长度大于3的部分,可以分解为多少个子Arithmetic Slices
开始的错误做法,不可取:错误之处:没有考虑数组A可以由几个连续部分组成,例如[1,2,3,7,8,9],而不仅仅是一个整的连续部分,像[1,2,3,4,5,6]。
但是最后的result的计算是根据从1到n连续N个数相加的求和公式sum=n*(n+1)/2,是突然想到的,不错不错,只是不适合本题。
public int numberOfArithmeticSlices(int[] A) {
if(A==null||A.length<3){
return 0;
}
int leng=A.length;
int result=0;
for(int i=0;i<leng-1;i++){
int minus=A[leng-1]-A[leng-2];
while(A[i+1]-A[i]==minus){
result=(leng-2)*(leng-1)/2;
}
}
return result;
}
因为A[i]-A[i-1]==A[i-1]-A[i-2]意味着只要有三个是连续的,就在这部分的总和eachPart上加1,然后向后移动,如果还有这部分的连续部分,就再加1,其他部分也是相同情况,最后把每部分的总和eachPart加起来就是sum。
public int numberOfArithmeticSlices(int[] A) {
if(A==null||A.length<3){
return 0;
}
int eachPart=0;
int sum=0;
int leng=A.length;
for(int i=2;i<leng;i++){
if(A[i]-A[i-1]==A[i-1]-A[i-2]){
eachPart=eachPart+1;
sum=sum+eachPart;
}else{
eachPart=0;
}
}
return sum;
}