題目描述:
小明很喜歡數學,有一天他在做數學作業時,要求計算出9~16的和,他馬上就寫出了正確答案是100。但是他並不滿足於此,他在想究竟有多少種連續的正數序列的和爲100(至少包括兩個數)。沒多久,他就得到另一組連續正數和爲100的序列:18,19,20,21,22。現在把問題交給你,你能不能也很快的找出所有和爲S的連續正數序列? Good Luck!
輸出所有和爲S的連續正數序列。序列內按照從小至大的順序,序列間按照開始數字從小到大的順序
思路:
利用雙指針形成滑動窗口,窗口的左右兩邊就是這兩個指針
- 得到當前窗口的值curSum,與給定的sum值作比較,初始化左右指針爲序列的前兩位。
- 如果curSum < sum ,右指針右移一位
- 如果curSum > sum,左指針右移一位
- 如果curSum = sum,將當前窗口的序列加入ArrayList集合中。
代碼:
package offer01;
import java.util.ArrayList;
public class TestNo41 {
public static void main(String[] args) {
System.out.println(new TestNo41().FindContinuousSequence(10));
}
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
int low = 1;
int high = 2;
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
while (low<high){
//由於是連續的,差爲1的一個序列,那麼求和公式是(a0+an)*n/2
int curSum = (low+high)*(high-low+1)/2;
if(curSum<sum){
high++;
}else if(curSum > sum){
low++;
}else{
ArrayList<Integer> list = new ArrayList<>();
for(int i= low;i<=high;i++){
list.add(i);
}
result.add(list);
low++;
}
}
return result;
}
}
長路浩浩蕩蕩 萬事皆可期待 ..