Java solution - very simple, O(n) time and O(1) space 2ms


  • 0
    C

    It needs a little math. 3 elements: 1 arithmetic, 4: 1+2=3 arithmetic, 5:1+2+3=6 arithmetic, n:len*(len+1)/2 . (len=n-2).
    Two if(len>=1) condition checks can also be removed to make codes more concise. But I would rather keep them to make logic clear.

    public int numberOfArithmeticSlices(int[] A) {
        if(A==null || A.length<=2) return 0;
        int count=0, len=0;
        for(int i=2; i<A.length; i++){
            if(A[i]-A[i-1]==A[i-1]-A[i-2]) len++;
            else{
                if(len>=1){
                    count+=len*(len+1)/2;
                }
                len=0;
            }
        }
        if(len>=1) count+=len*(len+1)/2;
        return count;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.