zoukankan      html  css  js  c++  java
  • 剑指offer——和为s的连续正整数序列

    输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。

    序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。

    示例 1:

    输入:target = 9
    输出:[[2,3,4],[4,5]]
    示例 2:

    输入:target = 15
    输出:[[1,2,3,4,5],[4,5,6],[7,8]]

    思路:此类带有“连续序列”字眼的题,一般操作是滑动窗口法。先设置一个大小为0的窗口,left=1, right=1, 窗口内的数字之和为sum,通过比较sum和target,不断扩大有边界或缩小左边界。

    class Solution {
    public:
        vector<vector<int>> findContinuousSequence(int target) {
            //滑动窗口左右边界
            int left = 1, right = 1;
            int sum = 0;
            vector<vector<int>> res;
            while(left <= target / 2) {    //超过target一半后不可能存在连续两个数之和为target
                if(sum < target) {      //sum < target则继续扩展右边界
                    sum += right;
                    right++;
                }
                else if(sum > target) {  //sum > target则缩小左边界
                    sum -= left;
                    left++;
                }
                else {            //找到了一个满足条件的序列
                    //记录结果
                    vector<int> vec;
                    //左开右闭的区间
                    for(int i = left; i < right; ++i) {
                        vec.push_back(i);
                    }
                    res.push_back(vec);
                    //左边界向右移动一格
                    sum -= left;
                    left++;
                }
            }
            return res;
        }
    };
  • 相关阅读:
    LeetCode_35.搜索插入位置
    LeetCode_349.两个数组的交集
    LeetCode_344.反转字符串
    LeetCode_34.在排序数组中查找元素的第一个和最后一个位置
    LeetCode_303.区域和检索
    LeetCode_3.无重复字符的最长子串
    LeetCode_292.Nim 游戏
    LeetCode_283.移动零
    LeetCode_27.移除元素
    LeetCode_268.丢失的数字
  • 原文地址:https://www.cnblogs.com/joker1937/p/12831224.html
Copyright © 2011-2022 走看看