1. 程式人生 > >LeetCode-413. Arithmetic Slices

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

一個while迴圈套一個for迴圈遍歷不知道為啥效率這麼高,交了第一次我還不信又交了一次還是1ms

solution:

class Solution {
    public int numberOfArithmeticSlices(int[] A) {
        if(A.length<3) //如果陣列長度小於3的話肯定沒有等差數列所以返回0
            return 0;
        int all = 0;  //最後要返回的結果
        int d = 0;    //公差
        int num = 1;  //儲存當前數列裡數的個數
        int head = 0; //儲存當前數列列首
        while(head<A.length-2){
            for(int i=head;i<A.length-1;i++){
                if(num==1){  //當num等於1時是作為求當前數列公差的判斷條件,如果num不等於1就應該將後續元素的差值與公差d作對比了
                    d = A[i+1]-A[i];
                    num++;
                }else{
                    if(d == A[i+1]-A[i]){
                        num++;
                        if(num>=3)
                            all+=1;
                    }else {  //因為等差數列是連續的所以如果不等差了就退出了但是退出前將num置為1即將下一個head元素入列
                        num = 1;
                        break;
                    }
                }

                if(i==A.length-2)
                    num=1;
            }
            head++;  //for迴圈遍歷以後要讓head++即找以下一個元素為首的等差數列
        }
        return all;
    }
}