剑指offer-和为S的连续正数序列

题目描述

小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

输出描述:

输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
 
使用数组保存当前序列,当前序列和>sum则减去数组第一个数字,当前序列和=sum则保存当前序列,
 1 public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {//my
 2         ArrayList<ArrayList<Integer>> re = new ArrayList<>();
 3         ArrayList<Integer> list = new ArrayList<>();
 4         int end = sum/2+1;
 5         int countSum =0;
 6         for(int i=1;i<=end;i++){
 7             list.add(i);
 8             countSum +=i;
 9             while(countSum>sum){
10                 countSum-=list.get(0);
11                 list.remove(0);
12             }
13             if(countSum==sum&&list.size()>1){
14                 ArrayList<Integer> l= new ArrayList<>();
15                 l.addAll(list);
16                 re.add(l);
17             }
18         }
19         return re;
20     }

记录当前序列两端的值,不用额外的数值保存当前的值

 1 public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {//mytip
 2         ArrayList<ArrayList<Integer>> re = new ArrayList<>();
 3         int i =1;
 4         int j =2;
 5         int end = sum/2+1;
 6         while(j<=end){
 7             int count = (i+j)*(j-i+1)/2;
 8             if(count==sum&&j!=i){
 9                 ArrayList<Integer> l= new ArrayList<>();
10                 for(int k =i;k<=j;k++){
11                     l.add(k);
12                 }
13                 re.add(l);
14                 j++;
15             }
16             else if(count>sum){
17                 i++;
18             }
19             else{
20                 j++;
21             }
22         }
23         return re;
24     }
 



猜你喜欢

转载自www.cnblogs.com/zhacai/p/10710668.html
今日推荐