41 and a continuous positive 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: The
output of all positive and continuous sequence S. The ascending order in the ascending sequence between the sequence numbers in accordance with the start ascending order

Ideas analysis

  • Violence Solution: Direct double loop
  • Double pointer / sliding window : the current window sum <a predetermined value, a left frame and the right pointer; sum = a predetermined value, the value added in the window list; sum> predetermined value, a left pointer left cell. Good idea!

Code

/**
 * 暴力解
 *
 * @param sum
 * @return
 */
public static ArrayList<ArrayList<Integer>> FindContinuousSequence1(int sum) {
    ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
    ArrayList<Integer> list = new ArrayList<>();
    int count = 0;
    for (int i = 1; i <= sum / 2; i++) {
        for (int j = i; j <= sum / 2 + 1; j++) {
            count += j;
            list.add(j);
            if (count == sum) {
                arrayLists.add(new ArrayList<>(list));
            } else if (count > sum) {
                break;
            }
        }
        count = 0;
        list.clear();
    }
    return arrayLists;
}

/**
 * 滑动窗口
 * @param sum
 * @return
 */
public static ArrayList<ArrayList<Integer>> FindContinuousSequence2(int sum) {
    ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();

    int start = 1, end = 2;
    while (end > start) {
        //求和公式
        int cursum = (end + start) * (end - start + 1) / 2;
        //相等
        if (cursum == sum) {
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = start; i <= end; i++) {
                list.add(i);
            }
            arrayLists.add(list);
            start++;
        } else if (cursum < sum) {
            //小了就扩大范围
            end++;
        } else {
            //大了就缩小范围
            start++;
        }
    }
    return arrayLists;
}
Published 118 original articles · won praise 8 · views 3720

Guess you like

Origin blog.csdn.net/qq_34761012/article/details/104443780