题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
思路:滑动窗口
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
//两个指针,相当于滑动窗口的两边
int plow = 1;
int phigh = 2;
//因为题干中说至少包含两个数,所以while不能取等号,否则会有sum这一个数加入到res中
while(plow < phigh){
ArrayList<Integer> list = new ArrayList<>();
int cur = (plow + phigh) * (phigh - plow + 1) / 2;//求和公式
//等,把数值都加入到list集合中
if(cur == sum){
for(int i = plow;i <= phigh;i++){
list.add(i);
}
res.add(list);
plow++;
}else if(cur < sum){//小于sum,右指针向右移,加入大的数
phigh++;
}else{//小于sum,左指针向右移,去掉最小的数
plow++;
}
}
return res;
}
}