Detailed sliding window problem

Sliding window is our daily said "double pointer", one after using two pointers, defined by determination of the condition, adjusting the relative position of the two hands, to meet our requirements.

Talk is cheap, Show me the code. Let's go directly to the practical exercise session. '

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

We first analyzed the little idea, and it requires a continuous output of all our positive series of S, Note that there are two defined conditions, positive first, followed by a continuous series. What is the smallest number of columns in continuous positive we can think of is? Yes 1 and 2. Second, he asked sequence from small to large numbers began to build, then we can get on-1 accumulates the number of columns.
The following is a specific problem-solving ideas

  • Create a double ArrayList array result as our return value
  • The two slider initial value, plow = 1 phigh = 2, while phigh> plow loop termination condition is our
  • A summing formula (phigh + plow) * (phigh - plow + 1) / 2 Equation judgment result of method parameters and the size of the case
  • Is equal to a new list, the entire plow to a value phigh added, and then the added result list
  • Less than the number is not big enough that we phigh ++
  • Is greater than the number that we too plow--

Through the above steps, the code is not hard to write a.

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

        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        int plow = 1, phigh = 2;
        while (phigh > plow) {
            if ((phigh + plow) * (phigh - plow + 1) / 2 == sum) {
                ArrayList<Integer> list = new ArrayList<>();
                for (int i = plow; i <= phigh; i++) {
                    list.add(i);
                }
                result.add(list);
                plow++;
            } else if ((phigh + plow) * (phigh - plow + 1) / 2 < sum) {
                phigh++;
            } else {
                plow++;
            }
        }
        return result;
    }

 

This article hopes to help you! !

Guess you like

Origin www.cnblogs.com/jiangtunan/p/11086951.html