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;
    }
}

 

相关文章:

  • 2022-01-29
  • 2022-12-23
  • 2022-12-23
  • 2022-01-21
  • 2021-09-02
  • 2021-08-03
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-13
  • 2022-02-16
  • 2021-11-23
  • 2021-07-01
  • 2021-12-08
  • 2022-12-23
相关资源
相似解决方案