題目描述
小明很喜歡數學,有一天他在做數學作業時,要求計算出9~16的和,他馬上就寫出了正確答案是100。但是他並不滿足於此,他在想究竟有多少種連續的正數序列的和爲100(至少包括兩個數)。沒多久,他就得到另一組連續正數和爲100的序列:18,19,20,21,22。現在把問題交給你,你能不能也很快的找出所有和爲S的連續正數序列? Good Luck!
輸出描述:
輸出所有和爲S的連續正數序列。序列內按照從小至大的順序,序列間按照開始數字從小到大的順序
解題思路
注意題中的關鍵信息 “連續正數序列” ,“從小至大的順序” ,可以用到一種巧妙的雙指針技術。雙指針技術,就是相當於有一個窗口,窗口的左右兩邊就是兩個指針,我們根據窗口內值之和來確定窗口的位置和寬度。
實現代碼
package Array;
import java.util.ArrayList;
/**
* @description:
* @author: Kevin
* @createDate: 2020/2/17
* @version: 1.0
*/
public class FindContinuousSequence {
public static void main(String[] args) {
FindContinuousSequence solution = new FindContinuousSequence();
int sum = 15;
ArrayList<ArrayList<Integer>> res = solution.FindContinuousSequence(sum);
System.out.println(res.toString());
}
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> > result = new ArrayList<>();
int plow = 1,phigh = 2;
while(phigh > plow){
int cur = (phigh + plow) * (phigh - plow + 1) / 2;
if(cur == sum){
ArrayList<Integer> list = new ArrayList<>();
for(int i=plow;i<=phigh;i++){
list.add(i);
}
result.add(list);
plow++;
}else if(cur < sum){
phigh++;
}else{
plow++;
}
}
return result;
}
}
圖解