小明很喜歡數學,有一天他在作數學做業時,要求計算出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 }