打卡系列-剑指 Offer 57 - II. 和为s的连续正数序列

    科技2022-07-20  107

    滑动窗口的应用

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

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

    public static int[][] findContinuousSequence(int target) { List<int[]> list = new ArrayList<>(); int _target = target / 2 + 1; int i = 1; int start = 1; int sum = 0; while (i <= _target){ if(sum + i < target){ sum += i; i++; }else if(sum + i == target){ sum += i; int[] arr = new int[i - start + 1]; generation(arr , start , i); list.add(arr); i++; }else { sum -= start; start++; } } int[][] second = new int[list.size()][]; for(i = 0 ; i < list.size() ;i++){ second[i] = list.get(i); } return second; } public static void generation(int[] a , int i , int j){ int k = 0; while (i <= j)a[k++] = i++; }

     

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    Processed: 0.017, SQL: 8