C++ One-pass Easy-Understand Solution without DP


  • 0
    C
    int continuous(int n){
        return n*(n-1)/2;
    }
    
    
    int numberOfArithmeticSlices(vector<int>& A) {
        if(A.size()<3)
            return 0;
        
        int answer=0;
        
        for(int i=A.size()-1;i>=1;i--)
            A[i]=A[i]-A[i-1];
        
        int pointer = 2;
        int counter = 1;
        int current = A[1];
        while(pointer!=A.size()){
            if(A[pointer]==current){
                counter++;
                pointer++;
            }else{
                answer += lianxu(counter);
                counter=1;
                current=A[pointer];
                pointer++;
            }
        }
        answer+=continuous(counter);
        return answer;
    }

Log in to reply
 

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