前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[剑指offer] 和为S的连续正数序列

[剑指offer] 和为S的连续正数序列

作者头像
尾尾部落
发布2018-09-04 15:19:01
4720
发布2018-09-04 15:19:01
举报
文章被收录于专栏:尾尾部落尾尾部落
题目描述

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

解题思路

滑动窗口的方法:用两个数字 start 和 end 分别表示序列的最小值和最大值,首先将 start 初始化为1,end 初始化为2。如果从start到end的和大于sum,我们就从序列中去掉较小的值(即增大start),

相反,只需要增大end。

终止条件为:一直增加begin到(1+sum)/2并且end小于sum为止

参考代码
代码语言:javascript
复制
import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
        ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
        if(sum < 3)
           return res;
        int start = 1, end = 2, mid = (1+sum)/2;
        while(start < mid){
            int s = totalSum(start, end);
            if(s == sum){
                res.add(getSequence(start, end));
                end ++;
            }else if(s < sum){
                end ++;
            }else if(s > sum){
                start ++;
            }
        }
        return res;
    }
    public int totalSum(int start, int end){
        int sum = 0;
        for(int i = start; i <= end; i++){
            sum += i;
        }
        return sum;
    }

    public ArrayList<Integer> getSequence(int start, int end){
        ArrayList<Integer> temp = new ArrayList<>();
        for(int i = start; i <= end; i++){
            temp.add(i);
        }
        return temp;
    }
}

版权属于: 尾尾部落

原文地址: https://cloud.tencent.com/developer/article/1327733

转载时必须以链接形式注明原始出处及本声明。

window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"1","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')0||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 解题思路
  • 参考代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档