和为S的连续正数序列
和为S的连续正数序列
http://www.nowcoder.com/questionTerminal/c451a3fd84b64cb19485dad758a55ebe
直接用了暴力法循环没想到过了。
其实用两支针法更好
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> > res = new ArrayList<>();
int temp = 0;//用来存储当前序列的和
for(int i=1;i<sum;i++){
temp+=i;
for(int j=i+1;j<sum;j++){
temp+=j;
if(temp==sum){
ArrayList<Integer> r = new ArrayList<>();
for(int k=i;k<=j;k++){
r.add(k);
}
res.add(r);
break;
}
}
temp=0;
}
return res;
}
查看9道真题和解析