剑指offer 041、和为S的连续正数序列
题目
题解
思路:
利用双指针技术,相当于有一个窗口,窗口的左右两边就是两个指针,我们根据窗口内值之和来确定窗口的位置和宽度。
注意,窗口始终是要往右移动的!不可以phigh--
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
if (sum == 1) return vector<vector<int> >();
vector<vector<int>> result; // 保存结果
int plow = 1, phigh = 2; // 双指针,根据窗口内的值之和确定窗口的大小和位置,plow要从1开始,不包含0
while (plow < phigh) {
// 连续数字之和公式:(a0+an)*n/2
int cur = (plow + phigh) * (phigh - plow + 1) / 2;
if (cur == sum) {
vector<int> temp;
for (int i = plow; i <= phigh; ++i) {
temp.push_back(i);
}
result.push_back(temp);
plow++; // 窗口要不断向右移动
}
else if (cur < sum) {
phigh++;
}
else {
// 当前窗口之和大于 sum,左边窗口右移
plow++;
}
}
return result;
}
};