输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。 序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/he… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
滑动窗口解题
难点在于 返回值 是一个 二维数组,利用 list.toArray(new int[0][]) 进行返回 对了,只需要遍历到 max = target / 2 + 1;
class Solution {
public int[][] findContinuousSequence(int target) {
List<int[]> list = new ArrayList<>();
int i = 1, j = 1;
int sum = 1;
int max = target / 2 + 1;
while (i <= max) {
if(sum < target) {
j++;
sum += j;
} else if ( sum > target) {
sum -= i;
i++;
} else {
int[] arr = new int[j - i + 1];
for (int x = i, k = 0; x <= j ; x++, k++) {
arr[k] = x;
}
list.add(arr);
sum -= i;
i++;
}
}
return list.toArray(new int[0][]);
}
}