1. 程式人生 > >【Leetcode】413. Arithmetic Slices

【Leetcode】413. Arithmetic Slices

class 初始 value code element 計數 final vat rip

Description

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.

Discuss

本題是一道動態規劃題,可以從最常見的動態規劃方法入手。原問題的求解可以轉換到子問題的求解。以例子為例[1, 2, 3, 4],數組長度為4,最小長度為3(題目規定),假設[1, 2, 3]已經是滿足題目要求的子序列,這時添加4進來,我們只需要判斷新添加進來的4和子序列最後一位 3 的差值和子序列的間距差是否相等。如果相等,則滿足要求,計數。時間復雜度較高,運行較慢。

看了網上別人的解法,使用的滑動窗口的思想。很簡潔,很快。大神還是厲害啊,還需要努力學習啊!

Code 1

class Solution {
    private static final int MAX = Integer.MAX_VALUE;
    public int numberOfArithmeticSlices(int[] A) {
        if (A == null || A.length < 3) { return 0; }
        int n = A.length;
        int[][] dp = new int[n][n];
        //初始化數組
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i - j < 2) { dp[j][i] = MAX; }
            }
        }

        int count = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= i - 2; j++) {
                if (i - j == 2) {
                    dp[j][i] = checkSlices(A, j, i);
                    if (dp[j][i] != MAX) { count++; }
                    continue;
                }
                dp[j][i] = (dp[j][i - 1] != MAX && A[i] - A[i - 1] == dp[j][i - 1]) ? dp[j][i - 1] : MAX;
                if (dp[j][i] != MAX) { count++; }
            }
        }
        return count;
    }

    public int checkSlices(int[] a, int left, int right) {
        int gap = a[left + 1] - a[left];
        int bb = a[right] - a[left + 1];
        if (gap == bb) {
            return bb;
        }
        return MAX;
    }
}

Code 2

class Solution {
    public int numberOfArithmeticSlices(int[] A) {
        if (A == null || A.length < 3) { return 0; }
        int res = 0;
        for (int i = 0; i < A.length; i++) {
            res = res + helper(A, i);
        }
        return res;
    }
    
    private int helper(int[] a, int start) {
        int index = start;
        int count = 0;
        
        while (index < a.length - 2 && a[index + 2] - a[index + 1] == a[index + 1] - a[index]) {
            index++;
            count++;
        }
        return count;
    }
}

【Leetcode】413. Arithmetic Slices