6 lines solution :Java in 2ms, C++ in 3ms, Javascript in 78ms


  • 1

    Walking on the "second" element of the arithmetic slices so we can deal with less corner cases or boundary checking.

    C++

        int numberOfArithmeticSlices(vector<int>& A) {
            int ret = 0,i,j;
            for(i=1;i<A.size();i=j) {
                for(j= i+1; j < A.size() && A[j] - A[j-1] == A[i] - A[i-1];++j);
                ret += (j-i) * (j-i-1) / 2;
            }
            return ret;
        }
    

    Java

        public int numberOfArithmeticSlices(int[] A) {
            int ret  = 0, i, j;
            for(i=1;i<A.length;i=j) {
                for(j=i+1; j<A.length && A[j] - A[j-1] == A[i] - A[i-1];++j);
                ret += (j-i)*(j-i-1)/2;
            }
            return ret;
        }
    

    Javascript

    var numberOfArithmeticSlices = function(A) {
        var ret=0, i,j;
        for(i=1;i<A.length;i=j) {
            for(j=i+1;j<A.length && A[j]-A[j-1] == A[i]-A[i-1];++j);
            ret += (j-i)*(j-i-1)/2;
        }
        return ret;
    };
    

    Go

    func numberOfArithmeticSlices(A []int) int {
        var ret,i,j int;
        for i,ret=1,0; i<len(A); i=j {
            for j=i+1;j<len(A) && A[j]-A[j-1] == A[i] - A[i-1];j++ {}
            ret += (j-i)*(j-i-1)/2;
        }
        return ret;
    }
    

Log in to reply
 

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