和为S的连续正数序列

https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe?tpId=13&tqId=11194&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

思路:利用双指针滑动窗口的思想。 窗口的左边left指向1,右边right指向2.

接下来判断窗口之间的数值和的大小与sum大小关系

当left < high的时候

如果current == sum ,得到一个序列,并且left++

如果current < sum则 right++

如果current > sum 则low++

 


class Solution {
public:
    vector<vector<int> > FindContinuousSequence(int sum)
	{
        vector<vector<int> >res;
		if(sum <= 0)
			return res;
		int low = 1, high = 2;
		while(low < high)
		{
			int current = (((high - low +1)*(low + high))>>1);
			if(current == sum)
			{
				vector<int>temp;
				for(int i = low ; i <= high; i++)
				{
					temp.push_back (i);

				}
				res.push_back (temp);
				low++;
			}
			else if(current < sum)
				high++;
			else if(current > sum)
				low++;
			
		}
		return res;
			  
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值