Very simple (7 lines) O(n)time, O(1)space java, C++ and C#


  • 0
    J
    java:
    public class Solution {
        public int numberOfArithmeticSlices(int[] A) {
            int sum = 0, b = 0;
            for(int i = 2; i < A.length; i++)
                if((A[i]- A[i-1]) == (A[i-1]- A[i-2]))
                    sum += (++b);
                else
                    b = 0;
            return sum;
        }
    }
    
    C++:
    class Solution {
    public:
        int numberOfArithmeticSlices(vector<int>& A) {
            int sum = 0, b = 0;
            for(int i = 2; i < A.size(); i++)
                if((A[i]- A[i-1]) == (A[i-1]- A[i-2]))
                    sum += (++b);
                else
                    b = 0;
            return sum;
        }
    };
    
    C#:
    public class Solution {
        public int NumberOfArithmeticSlices(int[] A) {
            int sum = 0, b = 0;
            for(int i = 2; i < A.Length; i++)
                if((A[i]- A[i-1]) == (A[i-1]- A[i-2]))
                    sum += (++b);
                else
                    b = 0;
            return sum;
        }
    }

Log in to reply
 

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