题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列?
Good Luck!
输出描述
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
分析
滑动窗口法,初始化low=1、high=2,计算当前窗口中的数字和,公式:(low+high)*n/2。根据窗口中的数字和sum与要求的和S进行比较调整窗口的大小。
1)sum>S,low++,左侧边界右移,窗口缩小;
2)sum<S,high++,右侧边界右移,窗口扩大;
3)sum=S,记录下当前窗口中数字,low++,找下一个满足条件的窗口。
代码
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> resultList = new ArrayList<>();
int low = 1, high = 2;
while(low<high){
int curSum = (low + high) * (high - low + 1 ) / 2;
if(curSum == sum){
ArrayList<Integer> tmp = new ArrayList<>();
for(int i=low;i<=high; i++) tmp.add(i);
resultList.add(tmp);
low++;
}else if(curSum<sum) high++;
else low++;
}
return resultList;
}
}




