題目描述
小明很喜歡數學,有一天他在做數學作業時,要求計算出9~16的和,他馬上就寫出了正確答案是100。但是他並不滿足於此,他在想究竟有多少種連續的正數序列的和爲100(至少包括兩個數)。沒多久,他就得到另一組連續正數和爲100的序列:18,19,20,21,22。現在把問題交給你,你能不能也很快的找出所有和爲S的連續正數序列? Good Luck!
思路:
看到這題,我首先想到的就是利用隊列求解。建一個隊列,從1開始,依次把小於S的數入隊,當隊列中數值的和爲S時,存儲下這個隊列,繼續入隊下一個數。當隊列中數的和大於S時,開始移除隊列中的數,直到隊列中數的和小於S。當隊列中數的和小於S時,接着入隊下一個小於S的數。如此循環操作,直到沒有小於S的數了。
代碼:
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
Queue<Integer> queue = new LinkedList<Integer>();
Queue<Integer> queue1 = new LinkedList<Integer>();
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
int num = 0;
Integer tempNum = 0;
//當sum小於3時,直接返回空
if(sum < 3){
return list;
}
for(int i=1;i<=sum;i++){
//當sum == num時,保存隊列中的正數序列
if(sum == num){
//創建臨時數組接受和爲S的連續序列
ArrayList<Integer> temp = new ArrayList<Integer>();
while((tempNum=queue.poll())!=null){
temp.add(tempNum);
queue1.offer(tempNum);
}
while((tempNum=queue1.poll())!=null){
queue.offer(tempNum);
}
list.add(temp);
queue.offer(i);
num = num + i;
}
//當num<sum時,入隊i
if(num < sum){
num = num + i;
queue.offer(i);
}
//當num > sum,出隊數據
if(num > sum){
while(num > sum){
num = num - queue.poll();
}
}
}
return list;
}
}