题目描述
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、起码是三个数及以上
2、相邻两个数之间差值相同
解题思路
1、设计struct xgr表示得到的子串,fir(第一个),last(最后一个),diff(差值)
2、先找出所有3个的子串
3、在3个的子串中慢慢扩展last直到无法扩展(根据last判断是否在t-1时是否扩展,否的话,以后都不需要考虑了)
re[j].last - re[j].fir + 1<= t - 2 )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;
}
};
本文介绍了一种算法,用于寻找数组中所有的算术切片,即等差序列。通过定义结构体存储子序列信息,并采用动态规划的思想,逐步扩展等差序列长度,最终统计出数组中所有符合条件的算术切片数量。
286

被折叠的 条评论
为什么被折叠?



