0%

LeetCode 413. Arithmetic Slices

题目

原题在此

解析

  1. 3个能构成1个Slices, 4个能构成1+2个, 5个能构成1+2+3个
  2. 每次比较三个就行, count每次比较成功就+1, 失败就归零.

代码

c++

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& A) {
int n = A.size(), cnt = 0, res = 0;
for(int i = 2; i < n; ++i){
if(A[i] - A[i - 1] == A[i - 1] - A[i - 2]) res += ++cnt;
else cnt = 0;
}
return res;
}
};