剑指offer-41.和为S的连续正数序列
2017-05-04 23:48
218 查看
题目:小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列?
Good Luck!
输出描述:
思路:利用高低指针,高低指针算出当前和,与给定和进行比较,如果当前和小于给定和,高指针加一,如果相等,进行回收,如果大于给定和,低指针加一。
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum)
{
vector<vector<int> >res;
int plow = 1, phigh = 2;
while (plow < phigh)
{
int cur = (phigh + plow) * (phigh - plow + 1) / 2;
if (cur < sum)
{
phigh++;
}
else if (cur == sum)
{
vector<int>temp;
for (int i = plow; i <= phigh; i++)
{
temp.push_back(i);
}
res.push_back(temp);
plow++;//别忘了低指针要更新
}
else
{
plow++;
}
}
return res;
}
};
Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
思路:利用高低指针,高低指针算出当前和,与给定和进行比较,如果当前和小于给定和,高指针加一,如果相等,进行回收,如果大于给定和,低指针加一。
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum)
{
vector<vector<int> >res;
int plow = 1, phigh = 2;
while (plow < phigh)
{
int cur = (phigh + plow) * (phigh - plow + 1) / 2;
if (cur < sum)
{
phigh++;
}
else if (cur == sum)
{
vector<int>temp;
for (int i = plow; i <= phigh; i++)
{
temp.push_back(i);
}
res.push_back(temp);
plow++;//别忘了低指针要更新
}
else
{
plow++;
}
}
return res;
}
};
相关文章推荐
- 剑指offer——41.和为S的连续正数序列
- 剑指Offer面试题41和为s的两个数字与和为s的连续正数序列,面试题42翻转单词顺序与左旋转字符串
- 剑指offer-面试题41:和为s的两个数字VS和为s的连续正数序列
- 剑指offer — 和为S的连续正数序列
- 剑指offer 和为S的连续正数序列
- 剑指offer题解 和为S的连续正数序列
- (C++)剑指offer-41:和为S的连续正数序列(知识迁移能力)
- 剑指Offer(57)和为S的连续正数序列
- 剑指Offer-面试题41-和为s 的两个数字vs 和为s 的连续正数序列
- 剑指offer---和为S的连续正数序列
- 【剑指offer-Java版】41和为s的两个数字VS和为s的连续正数序列
- 剑指offer 之 和为S的连续正数序列
- 剑指Offer:和为s的两个数字VS和为s的连续正数序列
- 【剑指offer-解题系列(42)】和为S的连续正数序列
- 剑指offer——和为s的两个数字VS和为s的连续正数序列
- 剑指offer——和为s的两个数字VS和为s的连续正数序列
- 【剑指offer】面试题57(2):和为S的连续正数序列
- 剑指offer 和为S的连续正数序列
- 剑指offer—和为S的连续正数序列
- 剑指Offer学习总结-和为S的连续正数序列