Leetcode 413. Arithmetic Slices

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

题意:给定一个数组,求该数组中等差数列的子数组的个数

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& A) {
if(A.size() == 0){
return 0;
}

int res = 0, cnt = 0;
for(int i = 2; i < A.size(); i++){
if(A[i] - A[i-1] == A[i-1] - A[i-2]){
cnt++;
res += cnt;
}
else{
cnt = 0;
}
}

return res;
}
};

0%