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.
题意没读懂:看了一下其他人的翻译
如果一组数包含至少3个元素,并且任意两个连续元素之差都相等,则称该序列为等差序列。
给定一个以0为起始下标的数组A,包含N个数字。数组的切片是指任意满足0 <= P < Q < N的整数对 (P, Q)。
数组A的切片 (P, Q) 是等差数列,如果满足下列条件:
A[P], A[p + 1], …, A[Q - 1], A[Q]是等差数列。特别的,P + 1 < Q。
函数应当返回数组A的等差数列切片的个数
其实一想还是很简单地,就是这个数组里有多少个长度大于等于3的等差数组
用dp
1 3 5 7 9 12 15 18 如果a-b=b-c 那么abc就是等差序列 现在指到5的位置 13 5是等差,接下来到7 如果7-5=5-3 那么3 5 7是等差,同时如果有以5结尾的等差数组那么7也可以放进去成为以7为结尾的等差数组(差值不变) 同时可以多一个以7为结尾的 长度为3的等差数组
所以有状态转移方程 最后求数组和即可
if(a[i]-a[i-1]==a[i-1]-a[i-2])
dp[i]=dp[i-1]+1;
public class Solution {
public int numberOfArithmeticSlices(int[] a) {
if(a==null||a.length==0) return 0;
int dp[]=new int[a.length];
for(int i=2;i<a.length;i++){
if(a[i]-a[i-1]==a[i-1]-a[i-2])
dp[i]=dp[i-1]+1;
}
int count=0;
for(int i=2;i<dp.length;i++)
count+=dp[i];
return count;
}
}