0
点赞
收藏
分享

微信扫一扫

剑指 Offer 57 - II. 和为s的连续正数序列I(java & python3)

伽马星系 2022-01-09 阅读 45

java:

感谢题解 学习一下滑动窗口 芜湖 

class Solution {
    public int[][] findContinuousSequence(int target) {
        int i = 1;
        int j = 1;
        int sum = 0;
        List<int[]> res = new ArrayList<>();

        while(i <= target / 2){
            if(sum < target){
                sum += j;
                j++;
            }else if(sum > target){
                sum -= i;
                i++;
            }else{
                int[] cur = new int[j - i];
                for(int k = i; k < j; k++){
                    cur[k - i] = k;
                }
                res.add(cur);
                sum -= i;
                i++;
            }
        }

        return res.toArray(new int[res.size()][]);

    }
}

python3:

class Solution:
    def findContinuousSequence(self, target: int) -> List[List[int]]:
        i, j, sums = 1, 1, 0
        res = []

        while i <= target // 2:
            if sums < target:
                sums += j
                j += 1
            elif sums > target:
                sums -= i
                i += 1
            else:
                arr = list(range(i, j))
                res.append(arr)
                sums -= i
                i += 1
        
        return res
举报

相关推荐

0 条评论