題目描述
給定一個正整數Num,請輸出所有連續的遞增的正整數序列,使得其和爲 Num。若不存在則輸出NULL。
根據要求完成編碼,提供main函數,要求考慮編碼可讀性和性能。
樣例輸入:
90
樣例輸出:
[2,3,4,5,6,7,8,9,10,11,12,13]
[6,7,8,9,10,11,12,13,14]
[16,17,18,19,20]
[21,22,23,24]
[29,30,31]
參考思路:很NB的思路!
雙指針技術,就是相當於有一個窗口,窗口的左右兩邊就是兩個指針,我們根據窗口內值之和來確定窗口的位置和寬度。
/**
* ContinuousPositiveInteger
* 和爲S的連續正整數序列
*/
import java.util.ArrayList;
public class ContinuousPositiveInteger
{
public static ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum)
{
ArrayList<ArrayList<Integer>> result = new ArrayList<>();//result是二維數組
//兩個起點,相當於動態窗口的兩邊,根據其窗口內的值的和來確定窗口的位置和大小
int low = 1, high=2;
while(high > low)
{
//由於是連續的,差爲1的一個序列,那麼求和公式是(a0+an)*n/2
int cur = (low + high)*(high - low + 1)/2;
//相等,那麼就將窗口範圍的所有數添加進結果集
if(cur == sum)
{
ArrayList<Integer> array = new ArrayList<>();
for(int i=low; i<=high; i++)
{
array.add(i);
}
result.add(array);//往二維數組裏填充數據
low++;//找到一種結果後,還有其他的可能性,繼續找可能的情況
}
//如果當前窗口內的值之和小於sum,那麼右邊窗口右移一下
else if(cur < sum)
{
high++;
}
//如果當前窗口內的值之和大於sum,那麼左邊窗口右移一下
else
{
low++;
}
}
return result;
}
public static void main(String[] args)
{
ArrayList<ArrayList<Integer>> temp;
Scanner sc = new Scanner(System.in);
//輸入整數Num
int Num = sc.nextInt();
temp = FindContinuousSequence(Num);
//二維ArrayList打印出結果
for(int i=0; i<temp.size(); i++)
{
System.out.println(temp.get(i));
}
}
}
後記:關於打印出來的形式
一開始我自己的想法是如下的代碼
for(int i=0; i<temp.size(); i++)
{
for(int j=0;j<temp.get(i).size(); j++)
{
//主要是雙引號,單引號會轉爲ASCII值相加
System.out.print(temp.get(i).get(j)+",");
}
System.out.println();
}
打印出來的結果如下,不能滿足題意。
90
2,3,4,5,6,7,8,9,10,11,12,13,
6,7,8,9,10,11,12,13,14,
16,17,18,19,20,
21,22,23,24,
29,30,31,