41. Sequence of consecutive positive numbers with sum S

Topic description

         Xiao Ming likes mathematics very much. One day when he was doing his math homework, he asked to calculate the sum of 9~16. He immediately wrote that the correct answer was 100;

         But he is not satisfied with this, he is thinking about how many kinds of continuous positive number sequences have a sum of 100 (including at least two numbers);

         It didn't take long for him to get another sequence of consecutive positive numbers summing to 100: 18, 19, 20, 21, 22. Now to you, can you also quickly find all sequences of consecutive positive numbers whose sum is S? Good Luck!

Output all sequences of consecutive positive numbers whose sum is S. The sequence is in ascending order, and the starting numbers are in ascending order among the sequences.

Problem solving ideas

          Double pointer problem, when the sum is less than sum, the large pointer continues +, otherwise the small pointer +

     public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
 
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();

        int phight = 2, plow = 1;

        while (phight > plow) {
            int curNum = (phight + plow) * (phight - plow + 1) / 2; // current sum

            if (curNum < sum) {
                phight++;
            } else if (curNum > sum) {
                plow++;
            } else {
                // if (curNum == sum)
                ArrayList<Integer> res = new ArrayList<>();
                for (int i = plow; i <= phight; i++) {
                    res.add(i);
                }
                result.add(res);

                plow++;
            }
        }
        return result;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325868255&siteId=291194637