首页 > 代码库 > arithmetic-slices

arithmetic-slices

 

https://leetcode.com/problems/arithmetic-slices/

public class Solution {
    public int numberOfArithmeticSlices(int[] A) {
        if (A.length < 3) {
            return 0;
        }

        int lastLen = 1;
        int lastDiff = A[1] - A[0];

        int ret = 0;
        for (int i=2; i<A.length; i++) {
            if (A[i] - A[i-1] == lastDiff) {
                // 这一步,很重要,因为增加的个数正好是lastLen
                ret += lastLen;
                lastLen++;
            }
            else {
                lastLen = 1;
                lastDiff = A[i] - A[i-1];
            }
        }
        return ret;
    }
}

 

arithmetic-slices