难度简单
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 1:
输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:
输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]
限制:
-
1 <= target <= 10^5
class Solution {
public int[][] findContinuousSequence(int target) {
List<int[]> list = new ArrayList<>();
int left = 1;
int right = 2;
int sum = 3;
while(left<right){
// System.out.println(sum);
if (sum ==target){
int[] array = new int[right-left+1];
for (int i = left; i <=right;i++){
array[i-left]=i;
}
list.add(array);
sum-=left;
left++;
}else if (sum <target){
right++;
sum+=right;
}else{
sum-=left;
left++;
}
}
return list.toArray(new int[list.size()][]);
}
}
class Solution {
public int[][] findContinuousSequence(int target) {
List<int[]> list = new ArrayList<>();
int left = 1;
int right = 2;
while(left<right){
int sum = (left + right) * (right - left + 1) / 2;
if (sum ==target){
int[] array = new int[right-left+1];
for (int i = left; i <=right;i++){
array[i-left]=i;
}
list.add(array);
left++;
}else if (sum <target){
right++;
}else{
left++;
}
}
return list.toArray(new int[list.size()][]);
}
}