To prove safety offer 41. knowledge of migration and continuous positive number sequence S

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
 

Problem-solving ideas

Double pointer technology, is the equivalent of a window, the window is two left and right pointers, we determine the position and width of the window according to the window value and

 

code show as below

 

public the ArrayList <the ArrayList <Integer>> FindContinuousSequence ( int SUM) {
          // store the results 
        the ArrayList <the ArrayList <Integer>> Result = new new the ArrayList <> ();
         // two starting points, corresponding to both sides of the dynamic window, the window according to their and the values to determine the location and the size of the window 
        int Plow = 1, Phigh = 2 ;
         the while (Phigh> Plow) {
             // because it is continuous, the difference of a sequence, then the summation formula is (a0 + AN) n-* / 2 
            int CUR = (+ Phigh Plow) * (Phigh - Plow +. 1) / 2 ;
             // equal, then the number of all window range will be added to the result set of 
            IF (CUR == SUM) { 
                the ArrayList <Integer> = List new newThe ArrayList <> ();
                 for ( int I = Plow; I <= Phigh; I ++ ) { 
                    List.add (I); 
                } 
                result.add (List); 
                Plow ++ ;
             // if the value within the current window and is smaller than the sum, then the right side of the window to the right look 
            } the else  IF (CUR < sUM) { 
                Phigh ++ ; 
            } the else {
             // If the sum is greater than the current window sum, then the left window to the right look 
                Plow ++ ; 
            } 
        } 
        return Result ;     
        
    }

 

Guess you like

Origin www.cnblogs.com/Transkai/p/11373969.html