题意:
给出一列数字,判断里面有多少个数列。(数列是一个长度至少为3,且所有相邻元素的差是一个值的一列数字)
分析:
我们要动态的描述一个区间:用开头和结尾描述。区间开始的长度为3.一旦不匹配(需要一个变量来描述相邻项的差,判断是不是数列,当然这是另一个子问题了,可以封装出去作一个函数)
我们来想象一个动态的遍历搜索过程:
1 如果区间是数列,那么结尾加1,直到不是数列或者区间结尾走到了数组结尾。
2 如果区间不是数列,那么开头加1,结尾重置为开头后面两位。
public class Solution {
public int numberOfArithmeticSlices(int[] A) {
int start = 0;
int end = 2;
int count = 0;
if(3 > A.length)
return 0;
while(start <= A.length-3){
if(end<=A.length-1 && isArithmetic(A, start, end)){ // &&左右条件如果颠倒函数内数组会越界
count++;
end++;
}else{
start++;
end = start+2;
}
}
return count;
}
public boolean isArithmetic(int[] a, int s, int e){
int d = a[s+1] - a[s];
while(s < e){
if(a[s+1]-a[s] == d){
s++;
}else{
return false;
}
}
return true;
}
}