和为s的连续正数序列(滑动窗口两个指针)
和为S的连续正数序列
http://www.nowcoder.com/questionTerminal/c451a3fd84b64cb19485dad758a55ebe
遍历数组判断和为sum 时间复杂度为O(n)
滑动窗口,设置两个指针i,j,当他们之间和小于sum j++,当和大于sum i--,和为sum 记录且i++寻找下一个满足的
class Solution { public: vector<vector<int> > FindContinuousSequence(int sum) { vector<vector<int> > ans; for(int i = 1; i <= sum/2;i++){ int tmp = 0; for(int k = i; k < sum;k++){ tmp += k; if(tmp>sum)break; if(sum == tmp){ vector<int> res; for(int j = i;j<=k;j++)res.push_back(j); ans.push_back(res); } } } return ans; } }; class Solution { public: vector<vector<int> > FindContinuousSequence(int sum) { vector<vector<int> > res; int ss=1,i=1,j=1; while(i<=sum/2){ // 当最小边界>sum/2时候结束,接下来i+j一定大于sum if(ss < sum) ss += ++j; //如果ss小于sum j++向右滑动,且ss+ = j记录和 if(ss == sum){ vector<int> ans; for(int k = i;k<=j;k++)ans.push_back(k); ss -= i++; // i左移动寻找下一个满足的情况 res.push_back(ans); } if(ss>sum)ss -= i++; } return res; } };