【剑指 Offer】 57 - II. 和为s的连续正数序列

发布时间 2023-04-16 09:21:47作者: 梦想是能睡八小时的猪

【题目】

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

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

 

示例 1:

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

示例 2:

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

 

限制:

    1 <= target <= 10^5

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof

【思路】

滑动窗口

初始i=1,j=2 i为左边界,j为右边界
1.滑动窗口内的值<target j右移
 2.滑动窗口内的值=target 保存 i右移
3.滑动窗口内的值>target i右移
当i>=j时,结束循环

这题注意list和array的转换的写法

 

【代码】

class Solution {
    public int[][] findContinuousSequence(int target) {
        //滑动窗口
        //初始i=1,j=2 i为左边界,j为右边界
        // 1.滑动窗口内的值<target j右移
        // 2.滑动窗口内的值=target 保存 i右移
        // 3.滑动窗口内的值>target i右移
        // 当i>=j时,结束循环

        int i = 1, j = 2;
        int sum = 3;
        List<int[]> result = new ArrayList<>();
        while(i<j){
            if(sum==target){
                int[] res = new int[j-i+1];
                for(int k=i,pos=0;k<=j;k++){
                    res[pos++] = k;
                }
                result.add(res);
                sum-=i;
                i++;         
            }
            else if(sum>target){
                sum-=i;
                i++;
            }else{
                j++;
                sum+=j;
            }
        }
        return result.toArray(new int[0][]);
    }
}