zoukankan      html  css  js  c++  java
  • 滑动窗口模板例题

    滑动窗口例题

    和为s的连续正数序列

    题目

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

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

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

    解法

    class Solution {
        public int[][] findContinuousSequence(int target) {
            List<int[]> res = new ArrayList<>();
            int sum = 0;
            for(int l = 1,r = 1;r < target;r++){//右边界自然后移
                sum+=r;
                while(sum > target){//左边界循环后移
                    sum-=l;
                    l++;
                }
                if(sum == target){
                    int[] temp = new int[r - l + 1];
                    for(int i = 0;i < temp.length;i++){
                        temp[i] = l+i;
                    }
                    res.add(temp);
                }
            }
            return res.toArray(new int[0][]);
        }
    }
    
  • 相关阅读:
    xml的建模
    P1341 无序字母对
    P1330 封锁阳光大学
    P2661 信息传递
    P1312 Mayan游戏
    P1514 引水入城
    C. Sad powers
    P1195 口袋的天空
    P1821 [USACO07FEB]银牛派对Silver Cow Party
    P1396 营救
  • 原文地址:https://www.cnblogs.com/wunsiang/p/12765174.html
Copyright © 2011-2022 走看看