小明很喜欢数学,有一天他在作数学做业时,要求计算出9~16的和,他立刻就写出了正确答案是100。可是他并不知足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就获得另外一组连续正数和为100的序列:18,19,20,21,22。如今把问题交给你,你能不能也很快的找出全部和为S的连续正数序列? Good Luck!
1 import java.util.ArrayList;
2 public class Solution {
3 public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
4 //存放结果
5 ArrayList<ArrayList<Integer>> result = new ArrayList<>();
6 //两个起点,至关于动态窗口的两边,根据窗口内的值的和来肯定窗口的位置和大小
7 int plow=1,phigh=2;
8 while(phigh>plow){
9 //因为是连续的,差为1的一个序列,那么求和公式为(a1+an)*n/2
10 int cur=(phigh+plow)*(phigh-plow+1)/2;
11 //相等,则将窗口中的值添加进结果集
12 if(cur==sum){
13 ArrayList<Integer> list = new ArrayList<>();
14 for(int i =plow;i<=phigh;i++){
15 list.add(i);
16 }
17 result.add(list);
18 plow++;
19 }else if(cur<sum){//若是当前窗口值之和小于sum,则右边窗口右移
20 phigh++;
21 }else{//若是当前窗口内的值之和大于sum,则左边窗口右移
22 plow++;
23 }
24 }
25 return result;
26 }
27 }