[Offer] [57-2] and [number of consecutive positive sequence S]

Title Description

  Enter a positive number s, and print out all consecutive positive sequence s (containing at least two numbers). For example, input 15, due to the 1 + 2 + 3 + 4 + 4 + 5 + 5 = 6 = 7 + 8 = 15, the print out of three consecutive sequence 1 to 5,4 to 6 and 7 to 8.

Cattle brush off questions address network

Ideas analysis

  We also consider two numbers big and small sequences of maximum and minimum values, respectively. First, the small initialized to 1, big initialized to 2. If s is greater than the sequence from small to big, and, the smaller value can be removed from the sequence, i.e. to increase the value of small. If the sequence from small to big, and is less than s, the big can be increased, so that the sequence contains more digits. Because this must be at least two sequence numbers, we have to increase the small (1 + s) until the / 2.
  

Test Case

  1. Functional test: the presence of a continuous sequence s and, as 9,100 like; and the absence of a continuous sequence s, and the like, such as 4,0.
  2. Boundary value testing: 3, and the minimum contiguous sequence.

Java code

public class Offer057_02 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();

    }

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

        return Solution1(sum);
    }

    private static ArrayList<ArrayList<Integer>> Solution1(int sum) {

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

        if (sum < 3) {
            return list;
        }
        int small = 1;
        int big = 2;
        int middle = (sum + 1) >> 1;
        int curSum = small + big;

        while (small < middle) {
            if (curSum == sum) {
                subList = add(small, big);
                list.add(subList);
            }
            while (curSum > sum && small < middle) {
                curSum -= sum;
                small++;
                if (curSum == sum) {
                    subList = add(small, big);
                    list.add(subList);
                }

            }
            big++;
            curSum += big;
        }

        return list;
    }

    private static ArrayList<Integer> add(int start, int end) {
        ArrayList<Integer> subList = new ArrayList<Integer>();
        for (int i = start; i <= end; i++) {
            subList.add(i);
        }
        return subList;
    }

    private static void test1() {

    }

    private static void test2() {

    }

    private static void test3() {

    }
}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer572-he-weis-de-lian-xu-zheng-shu-xu-lie.html