【剑指offer】【双指针】 57-II.和为s的连续正数序列
题目链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/
双指针
[l,r]的区间和:s = (l + r) * (r - l + 1) / 2
通过利用l和r两个指针,初始l=1,r=2;
如果s == target,将[l,r]的数组添加到结果res中,l++;
如果s < target, r++;
如果s > target, l++;
时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<vector<int>> findContinuousSequence(int target) {
vector<vector<int>> res;
vector<int> v;
int l = 1, r = 2;
while(l < r)
{
int sum = (l + r) * (r - l + 1) / 2;
if(sum == target){
v.clear();
for(int i = l; i <= r; ++i) v.push_back(i);
res.push_back(v);
l++;
}
else if(sum < target) r++;
else l++;
}
return res;
}
};
滑动窗口
不使用求和公式,比双指针效率更高些,减少多余的计算;
时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<vector<int>> findContinuousSequence(int target) {
vector<vector<int>> res;
for(int i = 1, j = 1, s = 1; i <= target / 2; i++)
{
while(s < target) j++, s += j;
if(s == target && j > i)
{
vector<int> v;
for(int k = i; k <= j; k++) v.push_back(k);
res.push_back(v);
}
s -= i;
}
return res;
}
};
知识的价值不在于占有,而在于使用