您的位置:首页 > 其它

《Cracking the Coding Interview》——第17章:普通题——题目12

2014-04-29 00:11 417 查看
2014-04-29 00:04

题目:给定一个整数数组,找出所有加起来为指定和的数对。

解法1:可以用哈希表保存数组元素,做到O(n)时间的算法。

代码:

// 17.12 Given an array of integers and target value, find all pairs in the array that sum up to the target.
// Use hash to achieve O(n) time complexity. Duplicates pairs are skipped.
#include <cstdio>
#include <unordered_map>
#include <vector>
using namespace std;

int main()
{
vector<int> v;
unordered_map<int, int> um;
int n, i;
int x, y;
int target;

while (scanf("%d", &n) == 1 && n > 0) {
scanf("%d", &target);

v.resize(n);
for (i = 0; i < n; ++i) {
scanf("%d", &v[i]);
}

// duplicate pairs are skipped
for (i = 0; i < n; ++i) {
um[v[i]] = um[v[i]] + 1;
}

unordered_map<int, int>::iterator it, it2;
for (it = um.begin(); it != um.end(); ++it) {
x = it->first;
y = target - x;
if (x > y) {
continue;
}

--it->second;
if ((it2 = um.find(y)) != um.end() && it2->second > 0) {
printf("(%d, %d)\n", x, y);
}
++it->second;
}

v.clear();
um.clear();
}

return 0;
}


解法2:先将数组排序,然后用两个iterator向中间靠拢进行扫描。总体时间是O(n * log(n))。

代码:

// 17.12 Given an array of integers and target value, find all pairs in the array that sum up to the target.
// O(n * log(n) + n) solution.
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;

int main()
{
vector<int> v;
int n, i;
int ll, rr;
int target;

while (scanf("%d", &n) == 1 && n > 0) {
scanf("%d", &target);

v.resize(n);
for (i = 0; i < n; ++i) {
scanf("%d", &v[i]);
}
sort(v.begin(), v.end());
ll = 0;
rr = n - 1;

int sum;
while (ll < rr) {
sum = v[ll] + v[rr];
if (sum < target) {
while (ll + 1 < rr && v[ll] == v[ll + 1]) {
++ll;
}
++ll;
} else if (sum > target) {
while (rr - 1 > ll && v[rr] == v[rr - 1]) {
--rr;
}
--rr;
} else {
printf("(%d, %d)\n", v[ll], v[rr]);
while (ll + 1 < rr && v[ll] == v[ll + 1]) {
++ll;
}
++ll;
}
}

v.clear();
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐