43. In a continuous and positive sequence S

Subject description:

  Xiao Ming is very fond of mathematics, one day when he was doing math homework, required to calculate and 9 to 16, he immediately wrote the correct answer is 100. But he was not satisfied with this, he wondered how many kinds of continuous positive number sequence is 100 (including at least two numbers). Before long, he got another set of consecutive positive number and a sequence of 100: 18,19,20,21,22. Now the question to you, you can also quickly identify all positive and continuous sequence S?

  All positive output and a continuous number sequence S. The ascending order in the ascending sequence between the sequence numbers in accordance with the start ascending order

Analysis of ideas:

  Known meaning of the questions, if the value of S is less than 3, then the discrete number sequence is positive and so that their presence is equal to S. When the value of S is less than 3, we set a window to receive a continuous sequence of positive numbers so that a value within the window, and S, with two windows defined as big and small pointers, the initial value is small. 1, big the initial value of 2, we must ensure that not more than half the value of small S value, because more than half if small then the value in the window and certainly larger than S. small sliding forward when the pointer value within the current window and is greater than S, big does not move. If the window is less than the value S so big to slide forward, small intact. When the window is equal to the value S, the result returned.

Code:

import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
       ArrayList<ArrayList<Integer>>res=new ArrayList<>();
       if(sum<3)
           return res;
        int small=1;
        int big=2;
        int mid=(sum+1)/2;  //small不能超mid
        int cursum=big+small;
        while(small<mid){
            if(cursum==sum)
                res.add(help(small,big));
            while(small<mid&&cursum>sum){
                cursum=cursum-small;
                small++;
                if(cursum==sum)
                    res.add(help(small,big));
            }
            big++;
            cursum=cursum+big;
        }
        return res;
    }
    public ArrayList<Integer>help(int small,int big){
        ArrayList<Integer>list=new ArrayList<>();
        for(int i=small;i<=big;i++){
            list.add(i);
        }
        return list;
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/10932672.html