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) == && n > ) {
scanf("%d", &target); v.resize(n);
for (i = ; i < n; ++i) {
scanf("%d", &v[i]);
} // duplicate pairs are skipped
for (i = ; i < n; ++i) {
um[v[i]] = um[v[i]] + ;
} 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 > ) {
printf("(%d, %d)\n", x, y);
}
++it->second;
} v.clear();
um.clear();
} return ;
}

解法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) == && n > ) {
scanf("%d", &target); v.resize(n);
for (i = ; i < n; ++i) {
scanf("%d", &v[i]);
}
sort(v.begin(), v.end());
ll = ;
rr = n - ; int sum;
while (ll < rr) {
sum = v[ll] + v[rr];
if (sum < target) {
while (ll + < rr && v[ll] == v[ll + ]) {
++ll;
}
++ll;
} else if (sum > target) {
while (rr - > ll && v[rr] == v[rr - ]) {
--rr;
}
--rr;
} else {
printf("(%d, %d)\n", v[ll], v[rr]);
while (ll + < rr && v[ll] == v[ll + ]) {
++ll;
}
++ll;
}
} v.clear();
} return ;
}

最新文章

  1. [翻译]AKKA笔记 - 有限状态机 -1
  2. C#调用SQL中的存储过程中有output参数,存储过程执行过程中返回信息
  3. react lazyload
  4. SQL-表的各种查查查
  5. 利用html 5 websocket做个山寨版web聊天室(手写C#服务器)
  6. JMeter中的关联-正则表达式提取(1)
  7. [实践] ubuntu下编译安装ambari
  8. 嵌入式 hi3518平台检测网线是否插上
  9. JSP中嵌入java代码的标签方式(转)
  10. [教程] 神器i9100刷基带与内核的方法!(兼带ROOT方法)
  11. Linux下给mysql创建用户分配权限
  12. 使用pabot并发执行robotframework的testSuite
  13. HDU5907 Find Q 数学
  14. SQL Server 数据库连接方法
  15. 销量预测和用户行为的分析--基于ERP的交易数据
  16. 详解Java中的clone方法
  17. 关于MQ,你必须知道的
  18. LVS负载均衡DR模式实现
  19. nslookup get public/external IP
  20. Spring2

热门文章

  1. MVC学习笔记:MVC实现用户登录验证ActionFilterAttribute用法并实现统一授权
  2. 笨办法学Python(二十)
  3. naive bayes classifier in data mining
  4. POJ-3041 Asteroids---二分图&amp;最小覆盖点
  5. 解决Gearman 报sqlite3错误
  6. Breaking Biscuits(模板题-求凸边形的宽)
  7. 旧文备份: CANopen的LSS子协议中文翻译
  8. Go标准库学习之OS常用函数
  9. 【ODT】cf896C - Willem, Chtholly and Seniorious
  10. 多任务版udp聊天器