小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
由题目可知信息:所需结果为 d=1,项数n 的和为S的等差数列。
等差数列的求和公式为 sum=(n*(a0+an)) / 2 ------- 由于 d=1,故 an=a0+n。
我们定义两个指针 plow、phight 来确定 n。
滑动窗口思想
public static ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
int plow=1, phight=2;
while(phight > plow){
//每次先判断当前段的sum总和
int cur = ((plow+phight) * (phight-plow+1))>>1;
if(cur == sum){ //倘若和等于结果,将整段数字添加进去
ArrayList<Integer> list = new ArrayList<>();
for(int i=plow; i<=phight; i++){
list.add(i);
}
result.add(list);
plow++; //记得更新plow
}else if(cur<sum){//如果当前窗口内的值之和小于sum,那么右边窗口右移一下
phight++;
}else{//如果当前窗口内的值之和大于sum,那么左边窗口右移一下
plow++;
}
}
return result;
}