您的位置:首页 > 职场人生

面试题45:和为s的两个数字VS和为s的连续正数序列

2016-01-13 14:20 387 查看
题目一:

输入一个递增排序的数组和一个数字s,在数组中查找两个数,是的它们的和正好是s。如果有多对数字的和等于s,输出任意一对即可。

思路:

由于数组已经排好序,可以从数组的头尾各取一个数字。

如果它们的和等于s,输出结果。

如果他们的和小于s,则前面的那个数往后一一个,重新判断。

如果它们的和大于s,则后面的那个数往前移动一个,重新判断。

知道出现相等或者前面的数和后面的数碰到。

时间复杂度:O(n)

代码略。

题目二:

输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以结果打印出3个连续序列。

思路:

用类似于题目一的方法,我们用两个数small和big来表示序列的最小值和最大值,small初始化为1,big初始化为2,如果序列的和小于s,则big增加1,如果序列的和大于s,则small增加1(即去掉序列中较小的值)。一直增加small到(1+s)/2。

#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <stack>
#include <algorithm>
#include <hash_set>  //for hashtable
#include <hash_map>
#include <unordered_map>
#include <set>
#include <ctime>
using namespace std;

using namespace std;

int GetSum(int small, int big)
{
int re = 0;
while (small <= big)
{
re += small;
small++;
}
return re;
}
vector<vector<int>>& GetContinuousSequeue(int s, vector<vector<int>>& res)
{
int small = 1, big = 2;
if (s < 3) return res;
while (small <= s / 2)
{
int sum = GetSum(small, big);
if (sum == s)
{
vector<int> temp;
for (int i = small; i <= big; ++i)
{
temp.push_back (i);
}
res.push_back(temp);
++small;
++big;
}
else if (sum < s) big++;
else small++;
}
return res;
}

int main()
{
vector<vector<int>> re;
GetContinuousSequeue(15,re);
for (int i = 0; i < re.size(); ++i)
{
for (int j = 0; j < re[i].size(); ++j)
cout << re[i][j] << " ";
cout << endl;
}
return 0;
}
不能将res定义在函数内,不然返回的地址是临时变量的地址,无效的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: