c++ solution 3ms


  • 0
    T
    class Solution {
    public:
        // count num of slices with length n array
        // from 3 to n-1 plus the whole array
        int count(int n) {
            int rst = 0;
            if (n >= 3) {
                for (int i = 3; i < n; ++i) rst += n-i+1;
                ++rst;
            }
            return rst;
        }
        int numberOfArithmeticSlices(vector<int>& A) {
            if (A.size() < 3) return 0;
            int nums = 0, d = A[1] - A[0], k = 2;
            for (int i = 2; i < A.size(); ++i) {
                if (d != A[i]-A[i-1]) {
                    nums += count(k);
                    d = A[i]-A[i-1]; k = 2;
                }
                else ++k;
            }
            nums += count(k);
            return nums;
        }
    };
    

Log in to reply
 

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