[Prove safety offer]

Title 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? Good Luck!

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

 

Topic links:

https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe?tpId=13&tqId=11194&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

 

 

 

 

 

package com.sunshine.OFFER66_SECOND;

import org.junit.Test;

import java.util.ArrayList;

public class A41_FindContinuousSequence {

    @Test
    public void test(){
        ArrayList<ArrayList<Integer>> arrayLists = FindContinuousSequence(2);
        arrayLists.forEach(a->{
            a.forEach(b->System.out.print(b+" "));
            System.out.println();
        });
    }


    public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        int curSum = 0;
        int left = 1;
        for (int i = 1; i <= (sum / 2 + 1); i++) {
            curSum += i;
            while (curSum > sum) {
                curSum -= left;
                left++;
            }
            if (curSum == sum) {
                if(i-left+1>=2) {
                    ArrayList<Integer> oneAns = newThe ArrayList <> ();
                     for ( int J = left; J <= I; J ++ ) { 
                        oneAns.add (J); 
                    } 
                    ans.add (oneAns); 
                } 
            } 
        } 
        return ANS; 
    } 
    
    // else solution, bis pointer, smaller than the right sum pointer ++, than the large sum left pointer ++
     // essentially the same not go into details. 
}

 

Guess you like

Origin www.cnblogs.com/MoonBeautiful/p/11468559.html