思路: 说是滑动窗口,我觉得称之为双指针法更合适;
相当于有一个窗口,窗口的左右两边就是两个指针,我们根据窗口内值之和来确定窗口的位置和宽度,
- 如果当前窗口内的值之和小于sum,那么右边窗口右移一下
- 如果当前窗口内的值之和大于sum,那么左边窗口右移一下
代码:
代码语言:javascript复制public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> res=new ArrayList<>();
int leftIndex = 1;
int rightIndex = 2;
while (rightIndex>leftIndex){
int curSum=(leftIndex rightIndex) * (rightIndex - leftIndex 1) / 2;
if (curSum>sum){
leftIndex ;
}else if (curSum<sum){
rightIndex ;
}else {
ArrayList<Integer> item=new ArrayList<>();
for (int i = leftIndex; i <=rightIndex ; i ) {
item.add(i);
}
res.add(item);
leftIndex ;
}
}
return res;
}