leetcode413. 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.

将包含大于等于三个元素且任意相邻两个元素之间的差相等的数组成为等差数列。现在输入一个随机数组,问该数组中一共可以找出多少组等差数列。

思路一:动态规划

假设已经知道以第i-1个数字为结尾有k个等差数列,且第i个元素与i-1号元素和i-2号元素构成了等差数列,则第i个数字为结尾的等差数列个数为k+1。因此我们可以自底向上动态规划,记录每一位作为结尾的等差数列的个数,并最终得出整个数列中等差数列的个数。代码如下:

    public int numberOfArithmeticSlices(int[] A) {
        int[] dp = new int[A.length];
        int count = 0;
        for(int i = 2 ; i

思路二:算数方法

首先看一个简单的等差数列1 2 3, 可知该数列中一共有1个等差数列
再看1 2 3 4, 可知该数列中一共有3个等差数列,其中以3为结尾的1个,以4为结尾的2个
再看1 2 3 4 5, 可知该数列中一共有6个等差数列,其中以3为结尾的1个,4为结尾的2个,5为结尾的3个。

综上,我们可以得出,如果是一个最大长度为n的等差数列,则该等差数列中一共包含的等差数列个数为(n-2+1)*(n-2)/2,即(n-1)*(n-2)/2

因此,我们只需要找到以当前起点为开始的最长的等差数列,计算该等差数列的长度并根据其长度得出其共包含多少个子等差数列。

代码如下:

    public int numberOfArithmeticSlices2(int[] A) {
        if(A.length <3) return 0;
        int diff = A[1]-A[0];
        int left = 0;
        int right = 2;
        int count = 0;
        while(right < A.length) {
            if(A[right] - A[right-1] != diff) {
                count += (right-left-1) * (right-left-2) / 2;
                diff = A[right] - A[right-1];
                left = right-1;
            }
            right++;
        }
        count += (right-left-1) * (right-left-2) / 2;
        return count;
    }

你可能感兴趣的:(leetcode,java,math,dp)