Prove safety: a continuous and 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 the input 15, due  1+2+3+4+5=4+5+6=7+8=15, it prints out the results of three consecutive sequences of 1 to 5,4 to 6 and 7 to 8.

Sample

Input: 15 

Output: [[ 1,2,3,4,5], [4,5,6], [7,8]]

Output Description:

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

 

solution

Two pointers  p, q indicate the minimum and maximum sequence. If the sequence is greater than s, the sequence is removed from a small value, i.e.  ++p; if the sequence is less than s, the sequence further comprises a digital right, i.e.  ++q.

S when p is more than half stopped.

 

 

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 p=1, q=2;
        int mid = (1+sum) >> 1;  //
        int curSum = p + q;
        while(p < mid){
            if(curSum == sum){
                res.add(getList(p, q));
            }
            
            while(curSum > sum && p < mid){
                curSum -= p;
                p++;
                if(curSum == sum){
                    res.add(getList(p, q));
                }
            }
            ++q;
            curSum += q;
        }
        return res;
    }
    
    private ArrayList<Integer> getList(int l, int r){
        ArrayList<Integer> res = new ArrayList<>();
        for(int i=l; i<=r; i++){
            res.add(i);
        }
        return res;
    }
}

 

Guess you like

Origin www.cnblogs.com/lisen10/p/11460402.html