1. 程式人生 > >面試題57-題目二:和為S的連續正數序列

面試題57-題目二:和為S的連續正數序列

/*

 * 面試題57-題目二:和為S的連續正數序列

 * 題目:輸出所有和為S的連續正數序列。序列內按照從小至大的順序,序列間按照開始數字從小到大的順序

 * 思路:定義兩個指標,分別遞增,尋找和為s的序列

 * 用兩個數字smallbig分別表示序列的最大值和最小值,首先將small初始化為1big初始化為2.

 * 如果從samllbig的和大於s,我們就從序列中去掉較小的值(即增大small),

 * 相反,只需要增大big

 * 終止條件為:一直增加small(1+sum)/2

 */

import java.util.ArrayList;

public

class No57FindContinuousSequence {

    public static void main(String[] args) {

       No57FindContinuousSequence n = new No57FindContinuousSequence();

       ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();

       lists = n.FindContinuousSequence(15);

       for (int i = 0; i < lists.size(); i++) {

           System.out.println(lists.get(i));

       }

    }

    public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {

       ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();

       if (sum < 3) {

           return lists;

       }

       int small = 1;

       int big = 2;

       while (small < (sum + 1) / 2) {

           int curSum = getSum(small, big);

           if (curSum < sum) {

              big++;

           } else if (curSum == sum) {

              ArrayList<Integer> list = new ArrayList<Integer>();

              for (int i = small; i <= big; i++) {

                  list.add(i);

              }

              lists.add(list);

              big++;

           }else {

              small++;

           }

       }

       return lists;

    }

    private int getSum(int small, int big) {

       int sum = 0;

       for(int i = small; i <= big; i++) {

           sum += i;

       }

       return sum;

    }

}