剑指offer 041、和为S的连续正数序列

剑指offer 041、和为S的连续正数序列

题目

image-20210922170106482

题解

思路:

利用双指针技术,相当于有一个窗口,窗口的左右两边就是两个指针,我们根据窗口内值之和来确定窗口的位置和宽度。

注意,窗口始终是要往右移动的!不可以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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ClimberCoding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值