輸出所有和為S的連續正數序列,序列內按照從小至大的順序,序列間按照開始數字從小到大的順序
解題思路
采用雙指標技術,就是相當于有一個視窗,視窗的左右兩邊就是兩個指標,我們根據視窗內值之和來確定視窗的位置和寬度,
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
// 存放結果
ArrayList<ArrayList<Integer>> results = new ArrayList<>();
// 兩個起點,相當于動態視窗的兩邊,根據其視窗內的值的和來確定視窗的位置和大小
int low = 1, high = 2;
while(high > low) {
// 由于是連續遞增的序列,求和公式是 (a0+an)*n/2
int cur = (low + high) * (high - low + 1) / 2;
// 相等,那么就將視窗范圍的所有數添加進結果集
if(cur == sum) {
ArrayList<Integer> list = new ArrayList<>();
for(int i = low; i <= high; i++) {
list.add(i);
}
results.add(list);
low++;
// 如果當前視窗內的值之和大于 sum,那么左邊視窗右移一下
} else if(cur > sum) {
low++;
// 如果當前視窗內的值之和小于 sum,那么右邊視窗右移一下
} else {
high++;
}
}
return results;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/186032.html
標籤:其他
上一篇:干貨分享:從零基礎到網路編程大牛,你只需這份網路編程入門指南
下一篇:和為 S 的兩個數字
