413. Arithmetic Slices

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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值