滑动窗口算法本质就像卷尺拉伸缩短测量,当不满足条件是向右拉伸,当满足条件时像左拉伸
滑动窗口框架
//左边界
int i=1;
//右边界
int j=1;
while(i<target){
if(条件1){
//右边界向右
sum+=j;
j++;
}else if(条件二){
//左边界向左
sum-=i;
i++;
}else{
//满足条件记录结果
//左边界向右移动
sum-=i;
i++;
}
}
剑指 Offer 57 - II. 和为s的连续正数序列 https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/
public int[][] findContinuousSequence(int target) {
//左边界
int i=1;
//右边界
int j=1;
int sum = 0;
List<int[]> list = new ArrayList<>();
while(i<target){
if(sum<target){
//右边界向右
sum+=j;
j++;
}else if(sum>target){
//左边界向左
sum-=i;
i++;
}else{
//满足条件记录结果
//System.out.println(i+","+j);
int[] tmp =new int[j-i];
for(int k=i;k<j;k++){
tmp[k-i] =k;
}
list.add(tmp);
//左边界向右移动
sum-=i;
i++;
}
}
return list.toArray(new int[list.size()][]);
}