标签:双指针 targe code i++ 空间复杂度 tor sequence get +=
[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;
int i = 1;
int j = 1;
int sum = 0;
while (i <= target / 2)
{
if (sum < target)
{
// 右边界向右移动
sum += j;
j++;
} else if (sum > target)
{
// 左边界向右移动
sum -= i;
i++;
} else
{
vector<int> arr;
for (int k = i; k < j; k++) arr.push_back(k);
res.push_back(arr);
// 左边界向右移动
sum -= i;
i++;
}
}
return res;
}
};
【剑指offer】【双指针】 57-II.和为s的连续正数序列
标签:双指针 targe code i++ 空间复杂度 tor sequence get +=
原文地址:https://www.cnblogs.com/Trevo/p/12730864.html