zoukankan      html  css  js  c++  java
  • 剑指Offer_41_和为S的连续正数序列

    题目描述

    小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

    输出描述:
    输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序

    解题思路

    用两个指针指向序列中最小值和最大值,当最小值到最大值的和大于给定值,那么最小值指针向后移动,小于给定值,则最大值指针向后移动,相等则序列就是要找的序列,然后最小值向后移动,继续寻找下一个,直到最小值指针到达(1+给定值)/ 2。

    实现

    import java.util.ArrayList;
    public class Solution {
        public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
            ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
            //if (sum <= 0) return lists;
            int sumNum = 0;
            int small = 1, big = 2;
            sumNum += small + big;
            while (small <= (1 + sum) / 2){
                if (sumNum < sum) {
                    big++;
                    sumNum += big;
                }else if (sumNum > sum){
                    sumNum -= small;
                    small ++;
                }else {
                    ArrayList<Integer> list = new ArrayList<>();
                    for (int i= small; i <= big; i++){
                        list.add(i);
                    }
                    lists.add(list);
                    sumNum -= small ++;
                }
            }
            return lists;
        }
    }
    
  • 相关阅读:
    Leetcode 811. Subdomain Visit Count
    Leetcode 70. Climbing Stairs
    Leetcode 509. Fibonacci Number
    Leetcode 771. Jewels and Stones
    Leetcode 217. Contains Duplicate
    MYSQL安装第三步报错
    .net 开发WEB程序
    JDK版本问题
    打开ECLIPSE 报failed to load the jni shared library
    ANSI_NULLS SQL语句
  • 原文地址:https://www.cnblogs.com/ggmfengyangdi/p/5798222.html
Copyright © 2011-2022 走看看