剑指offer_和为S的连续正整数序列

输出所有和为 S 的连续正数序列。 例如和为 100 的连续序列有: [9, 10, 11, 12, 13, 14, 15, 16] [18, 19, 20, 21, 22]。

方法一:利用等差数列公式,暴力解决

 1 import java.util.ArrayList;
 2 public class Solution {
 3     public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
 4         ArrayList<ArrayList<Integer> > ans = new ArrayList<>();
 5         for(int x=1;x<sum;x++){
 6            for(int n=1;n<sum;n++){
 7                if((2*x+n-1)*n==2*sum){
 8                     ArrayList<Integer> temp = new ArrayList<>();
 9                    for(int i=x;i<=x+n-1;i++)
10                        temp.add(i);
11                    ans.add(temp);
12                }
13            }
14        }
15         return ans;
16     }
17 }

方法二:

滑动窗口技巧

 1 import java.util.ArrayList;
 2 public class Solution {
 3     public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
 4         //存放结果
 5         ArrayList<ArrayList<Integer> > result = new ArrayList<>();
 6         //两个起点,相当于动态窗口的两边,根据其窗口内的值的和来确定窗口的位置和大小
 7         int plow = 1,phigh = 2;
 8         while(phigh > plow){
 9             //由于是连续的,差为1的一个序列,那么求和公式是(a0+an)*n/2
10             int cur = (phigh + plow) * (phigh - plow + 1) / 2;
11             //相等,那么就将窗口范围的所有数添加进结果集
12             if(cur == sum){
13                 ArrayList<Integer> list = new ArrayList<>();
14                 for(int i=plow;i<=phigh;i++){
15                     list.add(i);
16                 }
17                 result.add(list);
18                 plow++;
19             //如果当前窗口内的值之和小于sum,那么右边窗口右移一下
20             }else if(cur < sum){
21                 phigh++;
22             }else{
23             //如果当前窗口内的值之和大于sum,那么左边窗口右移一下
24                 plow++;
25             }
26         }
27         return result;
28     }
29 }

 

posted @ 2019-09-16 21:05  chyblogs  阅读(194)  评论(0)    收藏  举报