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