classSolution{// 左边界、右边界都只能往右走 publicint[][]findContinuousSequence(int target){ArrayList<int[]> ans =newArrayList<>();int left =1, right =1;int sum =0;// 推论1:满足题目要求的序列,最大开头为 target / 2while(left <= target /2){// 1. 增大窗口if(sum < target){sum += right++;}// 2. 缩小窗口:满足则加入,然后找 left + 1 开头的序列;否则直接寻找。else{// 序列满足的情况:加入答案if(sum == target){int[] ansArray =newint[right - left];for(int i =0; i < ansArray.length; i++){ansArray[i]= left + i;}ans.add(ansArray);}// 缩小sum -= left++;}}// 这行转化代码有必要记一下。。return ans.toArray(newint[ans.size()][]);}}
二刷
核心还是滑动窗口,注意维护。
数组的处理也要注意噢
classSolution{publicint[][]findContinuousSequence(int target){ArrayList<int[]> ans =newArrayList<>();int left =1, right =1;int sum =0;while(left <= target /2){if(sum < target){sum += right++;}else{if(sum == target){int[] arr =newint[right - left];for(int i =0; i < arr.length; i++){arr[i]= left + i;}ans.add(arr);}sum -= left++;}}return ans.toArray(newint[ans.size()][]);}}