和为S的连续正数序列

你快乐吗?

Posted by bbkgl on September 26, 2019

和为S的连续正数序列

C++,双指针。

用指针left、right维护一个窗口,将窗口内所有数之和与sum对比,然后根据结果调整窗口大小。如果大,left++,如果小,right++。

等差数列求和。。。

class Solution {
public:
    vector<vector<int>> FindContinuousSequence(int sum) {
        vector<vector<int>> ans;
        int left = 1, right = 2;
        while (left < right) {
            int tsum = (left + right) * (right - left + 1) / 2;
            if (tsum == sum) {
                vector<int> v;
                for (int i = left; i <= right; i++) v.push_back(i);
                ans.push_back(v);
                left++;
            } else if (tsum < sum)
                right++;
            else
                left++;
        }
        return ans;
    }
};