面试题57 - II. 和为s的连续正数序列

https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/

滑动窗口就可以解决这个题目

class Solution {
    public int[][] findContinuousSequence(int target) {
        List<int[]> list = new ArrayList<>();
        int slow = 1;
        int count = 0;
        for(int fast = 1; fast <= target/2 + 1; fast++){
            count += fast;
            if(count > target) {
                while (count > target) {
                    count -= slow;
                    slow++;
                }
            }
            if(count == target){
                int[] temp = new int[fast - slow + 1];
                int index = 0;
                for(int i = slow; i <= fast; i++){
                    temp[index++] = i;
                }
                list.add(temp);
            }
        }
        int[][] res = new int[list.size()][];
        for(int i = 0; i < list.size(); i++){
            res[i] = list.get(i);
        }
        return res;
    }
}

如果连续和大于target,就从小号开始删起,直到count小于等于target

posted @ 2020-05-09 13:19  ZJPang  阅读(156)  评论(0编辑  收藏  举报