題目描述
小明很喜歡數學,有一天他在做數學作業時,要求計算出9~16的和,他馬上就寫出了正確答案是100。但是他並不滿足於此,他在想究竟有多少種連續的正數序列的和爲100(至少包括兩個數)。沒多久,他就得到另一組連續正數和爲100的序列:18,19,20,21,22。現在把問題交給你,你能不能也很快的找出所有和爲S的連續正數序列?
Good Luck!
輸出描述
輸出所有和爲S的連續正數序列。序列內按照從小至大的順序,序列間按照開始數字從小到大的順序
分析
滑動窗口法,初始化low=1、high=2,計算當前窗口中的數字和,公式:(low+high)*n/2。根據窗口中的數字和sum與要求的和S進行比較調整窗口的大小。
1)sum>S,low++,左側邊界右移,窗口縮小;
2)sum<S,high++,右側邊界右移,窗口擴大;
3)sum=S,記錄下當前窗口中數字,low++,找下一個滿足條件的窗口。
代碼
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> resultList = new ArrayList<>();
int low = 1, high = 2;
while(low<high){
int curSum = (low + high) * (high - low + 1 ) / 2;
if(curSum == sum){
ArrayList<Integer> tmp = new ArrayList<>();
for(int i=low;i<=high; i++) tmp.add(i);
resultList.add(tmp);
low++;
}else if(curSum<sum) high++;
else low++;
}
return resultList;
}
}