码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-09-08 21:43:39      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:题目   ack   turn   ==   amp   循环条件   back   font   并且   

题目描述

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

输出描述:

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

思路:定义两个变量small和big,如果[small,big]之间的和tmp大于sum,那么tmp - small,并且++small;
如果他们之间的和小于sum,那么就++big,tmp += big,注意循环条件是small 要小于(1 + sum) / 2;因为如果small =(1 + sum) / 2;那么至少有两个数加起来肯定大于sum不符合条件。
class Solution {
public:
    vector<int> rowResult(int start,int end){
        vector<int> res;
        for(int i = start;i <= end;++i){
            res.push_back(i);
        }
        return res;
    }
    vector<vector<int> > FindContinuousSequence(int sum) {
        vector<vector<int> > result;
        if(sum < 3){
            return result;
        }
        int small = 1,big = 2;
        int mid = (1 + sum) / 2;
        int tmp = small + big;
        while(small < mid){
            if(tmp == sum){
                result.push_back(rowResult(small,big));
            }
            while(small < mid && tmp > sum){
                tmp -= small;
                ++small;
                if(tmp == sum){
                    result.push_back(rowResult(small,big));
                }
            }
            ++big;
            tmp += big;
        }
        return result;
    }
};

 

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

标签:题目   ack   turn   ==   amp   循环条件   back   font   并且   

原文地址:http://www.cnblogs.com/dingxiaoqiang/p/7496293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!