python solution with detailed explanation (45ms)


  • 2
    class Solution(object):
        def numberOfArithmeticSlices(self, A):
            """
            :type A: List[int]
            :rtype: int
            """
            if A==None or len(A)<3:
                return 0
            sliceL=[]
            i=0
            while i < len(A)-2:
                j=i+1
                dif=A[j]-A[i]
                while j<len(A) and A[j]-A[j-1]==dif:
                    j+=1
                if j-i>=3:
                   if A[i:j] not in sliceL:
                        sliceL.append(A[i:j])
                   i=j #slide the window as more as possible
                else:
                    i+=1
            #count the total number of slice
            #for example [1,2,3] n=1
            #[1,2,3,4] ,n=1+2=3 [1,2,3,4],[1,2,3],[2,3,4]
            #[1,2,3,4,5],n=1+2+3=6 [1,2,3,4,5],[1,2,3,4],[2,3,4,5],[1,2,3],[2,3,4],[3,4,5]
            cnt=0
            for slice in sliceL:
                sL=len(slice)
                cnt+=(1+sL-2)*(sL-2)//2
            return cnt
    

Log in to reply
 

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