41. 和为S的连续正数序列

◇◆丶佛笑我妖孽 提交于 2019-12-27 01:44:37

题目描述

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

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

1. 滑窗

代码实现

/**
 * @Classname Solution
 * @Description TODO
 * @Date 2019/12/22 13:02
 * @Author SonnSei
 */
public class Solution {
    public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer>> ret= new ArrayList<>();
        if(sum<3)return ret;
        ArrayList<Integer> temp = new ArrayList<>();
        int left = 1, right = 2,tempSum = 3;
        temp.add(left);
        temp.add(right);
        while (right < sum && left < right) {
            if (tempSum == sum) {
                ret.add(new ArrayList<>(temp));
                temp.remove(0);
                tempSum-=left++;
                tempSum+=++right;
                temp.add(right);
            } else if (tempSum > sum) {
                temp.remove(0);
                tempSum-=left;
                left++;
            } else {
                tempSum+=++right;
                temp.add(right);
            }
        }
        return ret;
    }
}

复杂度分析

显然时间复杂度是O(n){O(n)},也只用到了两个指针和一个tempSum变量,所以空间复杂度是O(1){O(1)}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!