https://leetcode.com/problems/arithmetic-slices/description/
int numberOfArithmeticSlices(vector<int>& A) {
if(A.size()<3) return 0;
int N = A.size();
A.push_back(A.back() + A[N-1] - A[N-2] -1);
int k=2, d=A[1]-A[0];
int res = 0;
for(int i=2; i<A.size(); i++) {
if(d == A[i] - A[i-1]) k++;
else {
if(k>=3) res += (k-1)*(k-2)/2;
k=2;
d = A[i] - A[i-1];
}
}
return res;
}
No comments:
Post a Comment