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

时间:2020-05-09
本文章向大家介绍面试题57 - II. 和为s的连续正数序列,主要包括面试题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

原文地址:https://www.cnblogs.com/ZJPaang/p/12856692.html