和为S的连续正数序列
和为S的连续正数序列
http://www.nowcoder.com/questionTerminal/c451a3fd84b64cb19485dad758a55ebe
import java.util.ArrayList; public class Solution { public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> slist=new ArrayList<>(); ArrayList<Integer> list=new ArrayList<>(); if(sum<3){//不满足至少两个连续正数合为sum return slist; } int small=1,big=2;//初始化双指针 int mid=(1+sum)/2; int cursum=small+big; while(small<mid){ if(cursum==sum){ list=res(small,big); slist.add(list); } while(cursum>sum&&small<mid){ cursum=cursum-small; small++; if(cursum==sum){ list=res(small,big); slist.add(list); } } big++; cursum=cursum+big; } return slist; } //添加连续正数序列中的元素 public ArrayList<Integer> res(int small,int big){ ArrayList<Integer> list=new ArrayList<>(); for(int i=small;i<=big;i++){ list.add(i); } return list; } }