My simple 0(n) time,0(1) space,single pass java solution


  • 0
    D
    public class Solution {
        public int numberOfArithmeticSlices(int[] A) {
            if(A.length<3)
                return 0;
                
            int streak=0,diff=0,ret=0;
            if((A[1]-A[0])==(A[2]-A[1]))
            {
                ++streak;
            }
            diff = A[2]-A[1];
            for(int i=2;i<A.length-1;i++)
            {
                if((A[i]-A[i-1])==(A[i+1]-A[i]))
                {
                    if(diff == (A[i+1]-A[i]))
                    {
                        ++streak;
                    }
                    else
                    {
                        diff = (A[i+1]-A[i]);
                        streak=1;
                    }
                }
                else
                {
                    ret = ret + ((streak * (streak+1))/2);
                    streak=0;
                }
            }
            ret = ret + ((streak * (streak+1))/2);
            
            return ret;
        }
    }
    

Log in to reply
 

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