剑指offer 和为S的连续正数序列
2017-04-16 14:43
423 查看
题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck! 输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
思路:连续,其实类似二分查找的过程,sum=100,如果由5个数连续组成,那么一定是20(mid)附近的数。而且条件也给出最少为2个数。在分析特点,开始的数一定小于mid,mid<end, 如果没有满足的数,则增1继续判断。
class Solution{
public:
vector<vector<int>> FindContinuousSequence(int sum){
vector<vector<int>> res;
if(sum<3) return res;
int mid=(sum+1)>>1;
int begin=1;
int end=2;
int cur=begin+end;
while(begin<mid&&end<sum){
while(cur>sum){
cur-=begin;
begin++;
}
if(cur==sum)
InsertRes(begin,end,res);
end++;
cur+=end;
}
return res;
}
void InsertRes(int begin,int end,vector<vector<int>> &res){
vector<int> temp;
for(int i=begin;i<=end;i++)
temp.push_back(i);
res.push_back(temp);
}
};
相关文章推荐
- 剑指offer--和为S的连续正数序列
- 剑指offer-和为S的连续正数序列-两根指针
- 剑指offer:和为S的连续正数序列
- 剑指offer——和为s的两个数字VS和为s的连续正数序列
- 【剑指Offer面试编程题】题目1354:和为S的连续正数序列--九度OJ
- 剑指offer:和为 s 的连续正数序列
- 剑指offer——面试题41:和为s的两个数字VS和为s的连续正数序列
- 剑指offer——和为s的连续正数序列
- 剑指Offer_面试题41_和为s的两个数字 VS 和为s的连续正数序列
- 剑指Offer——输入正整数S,打印出所有和为S的连续正数序列(至少含有两个正数)
- 剑指Offer 41题 和为s的两个数字VS 何为S的连续正数序列 Java版
- 码农小汪剑指Offer之39-和为S的连续正数序列
- 【剑指Offer面试编程题】题目1354:和为S的连续正数序列--九度OJ
- 剑指offer--和为S的连续正数序列
- 【剑指offer】和为定值的连续正数序列
- 【剑指offer】Q41:和为s的连续正数序列
- 剑指Offer: 和为S的连续正数序列
- (C++)剑指offer-41:和为S的连续正数序列(知识迁移能力)
- 剑指Offer(57)和为S的连续正数序列
- 剑指offer---和为s的两个数字VS和为s的连续正数序列