《Cracking the Coding Interview》——第17章:普通题——题目12
2014-04-29 00:11
417 查看
2014-04-29 00:04
题目:给定一个整数数组,找出所有加起来为指定和的数对。
解法1:可以用哈希表保存数组元素,做到O(n)时间的算法。
代码:
解法2:先将数组排序,然后用两个iterator向中间靠拢进行扫描。总体时间是O(n * log(n))。
代码:
题目:给定一个整数数组,找出所有加起来为指定和的数对。
解法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; }
相关文章推荐
- 《Cracking the Coding Interview》——第17章:普通题——题目11
- 《Cracking the Coding Interview》——第17章:普通题——题目4
- 《Cracking the Coding Interview》——第17章:普通题——题目13
- 《Cracking the Coding Interview》——第17章:普通题——题目5
- 《Cracking the Coding Interview》——第17章:普通题——题目14
- 《Cracking the Coding Interview》——第17章:普通题——题目6
- 《Cracking the Coding Interview》——第17章:普通题——题目7
- 《Cracking the Coding Interview》——第17章:普通题——题目8
- 《Cracking the Coding Interview》——第17章:普通题——题目1
- 《Cracking the Coding Interview》——第17章:普通题——题目2
- 《Cracking the Coding Interview》——第17章:普通题——题目9
- 《Cracking the Coding Interview》——第17章:普通题——题目3
- 《Cracking the Coding Interview》——第17章:普通题——题目10
- 《Cracking the Coding Interview》——第18章:难题——题目12
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目6
- 《Cracking the Coding Interview》——第3章:栈和队列——题目3
- 《Cracking the Coding Interview》——第4章:树和图——题目9
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目4
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目2
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目8