题干:
A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.
A slice (P, Q) of array A is called arithmetic if the sequence:
A[P], A[p + 1], …, A[Q – 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.
The function should return the number of arithmetic slices in the array A.
Example:
A = [1, 2, 3, 4]
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
题目解析:
1、设计struct xgr表示得到的子串,fir(第一个),last(最后一个),diff(差值)
2、先找出所有3个的子串
3、在3个的子串中慢慢扩展last直到无法扩展(根据last判断是否在t-1时是否扩展,否的话,以后都不需要考虑了)
4、count在扩展时计数
class Solution {
public:
struct xgr {
int fir;
int last;
int diff;
xgr(int a, int b, int c):fir(a), last(b), diff(c){}
};
int numberOfArithmeticSlices(vector<int>& A) {
vector<xgr> re;
if(A.empty() || A.size() < 3)
return 0;
for (int i = 0; i < A.size() - 2; i++) {
if (A[i + 1] - A[i] == A[i + 2] - A[i + 1]) {
int fir = i;
int last = i + 2;
int diff = A[i + 1] - A[i];
re.push_back(xgr(fir, last, diff));
}
}
if (re.empty())
return 0;
int count = re.size();
for (int t = 4; t <= A.size(); t++) {
for (int j = 0; j < re.size(); j++) {
if ((re[j].last - re[j].fir + 1<= t - 2 )|| (re[j].last + 1 >= A.size()))
continue;
if (A[re[j].last + 1] - A[re[j].last] == re[j].diff) {
count++;
re[j].last++;
}
}
}
return count;
}
};