my clear java solution O(n)


  • 0
    S

    //math, A contains n element, result is arithmetic series add by one each
    // n = 3 is 1, n = 4 is 1+2, n = 5 is 1+2+3

    public class Solution {
        public int numberOfArithmeticSlices(int[] A) {
    
            int sum = 0, add = 0;
            for(int i = 0; i < A.length -2; i++){
                if(A[i]-A[i+1] == A[i+1]-A[i+2]){
                    add++;
                    sum += add;
                }
                else
                    add = 0;
            }
            return sum;
        }
    }
    

    if you can not understand arithmetic progression by"add", just use result n(n-1)/2;
    //math, A contains n element, result is (1+n-2)*(n-2)/2

    public class Solution {
        public int numberOfArithmeticSlices(int[] A) {
    
                   if(A.length < 3) return 0;
            int res = 0;
            int len = 2;
            for(int i = 0; i <= A.length-3; i++){
                if((A[i]-A[i+1]) == (A[i+1]-A[i+2])){ 
                    len++;
                    if((i+2) == A.length-1) res += (len-1)*(len-2)/2;
                }
                else{ 
                    if(len > 2) res += (len-1)*(len-2)/2;
                    len = 2;
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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