Two Sum(hashtable)
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
三种做法:
1.暴力O(n2),找出所有两两数之和,判断是否与target相等,若相等则结束。
2.位置记录,map。由于map的键是自动排序的,所以直接对其进行操作即可
3.参考别人,读完题首先想到的就是两层遍历法,但是显然时间复杂度太高,是O(N^2),不符合要求,于是就应该想如何降低复杂度,首先应该想将逐个比较转变为直接查找,即首先计算出 target与当前元素的差,然后在序列中寻找这个差值,这样首先就把问题简化了,而寻找的过程可以先对序列进行快排,然后二分查找,这样整体的复杂度就降低为 O(N*logN) 了;查找最快的方法是利用一个 map容器存储每个元素的索引,这样取得某个特定元素的索引只需要常数时间即可完成,这样就更快了,最多只需遍历一次序列,将元素及其索引加入map中,在遍历的过程中进行对应差值的查找,如果找到了就结束遍历,这样时间复杂度最多为 O(N)
方法2代码:注意重复的判断,如numbers={0,3,4,0},target=0;由于题目已假设只有一个解决方案,所以若numbers有重复,则重复的这个数,只可能和本身构成target。
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int len=numbers.size();
map<int,int> m;
vector<int> res;
for(int i=;i<len;++i){
if (!m[numbers[i]])
{
m[numbers[i]]=i+;
}else
{
if(numbers[i]+numbers[i]==target){
res.push_back(m[numbers[i]]);
res.push_back(i+);
return res;
}
}
}
map<int,int>::iterator it_beg=m.begin();
map<int,int>::iterator it_end=m.end();
--it_end; while(it_beg!=m.end()&&it_end!=m.begin()){
if(it_beg->first+it_end->first>target)
--it_end;
else if(it_beg->first+it_end->first<target)
++it_beg;
else{
res.push_back(it_beg->second);
res.push_back(it_end->second);
if(res[]>res[])
swap(res[],res[]);
return res;
} }
}
};
方法三代码:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int i, sum;
vector<int> results;
map<int, int> hmap;
for(i=; i<numbers.size(); i++){
if(!hmap.count(numbers[i]))
hmap.insert(pair<int, int>(numbers[i], i));
if(hmap.count(target-numbers[i])){
int n=hmap[target-numbers[i]];
if(n<i){//两个作用:自身等于target排除,若有重复,找出较小的即n
results.push_back(n+);
results.push_back(i+);
return results;
} }
}
return results;
}
};
Two Sum(hashtable)的更多相关文章
- js实现哈希表(HashTable)
在算法中,尤其是有关数组的算法中,哈希表的使用可以很好的解决问题,所以这篇文章会记录一些有关js实现哈希表并给出解决实际问题的例子. 第一部分:相关知识点 属性的枚举: var person = { ...
- HDU-1003:Max Sum(优化)
Max Sum Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Sub ...
- java数据结构——哈希表(HashTable)
哈希表提供了快速的插入操作和查找操作,每一个元素是一个key-value对,其基于数组来实现. 一.Java中HashMap与Hashtable的区别: HashMap可以接受null键值和值,而Ha ...
- Maximum Subsequence Sum(java)
7-1 Maximum Subsequence Sum(25 分) Given a sequence of K integers { N1, N2, ..., NK }. A con ...
- UVALive - 7639 G - Extreme XOR Sum(思维)
题目链接 题意 给出一个序列,相邻两两异或,生成一个新序列,再相邻两两异或,直到只剩下一个元素,问最后结果为多少.m个查询,每次都有一个待查询区间. 分析 既然有多组查询,n只是1e4,那么可以考虑预 ...
- LeetCode:39. Combination Sum(Medium)
1. 原题链接 https://leetcode.com/problems/combination-sum/description/ 2. 题目要求 给定一个整型数组candidates[ ]和目标值 ...
- 「LeetCode」0001-Two Sum(Ruby)
题意与分析 题意直接给出来了:给定一个数,返回数组中和为该数(下为\(x\))的两个数的下标. 这里有一个显然的\(O(n)\)的实现:建立一个hash表,每次读入数(记作\(p\))的时候查询has ...
- leetcode 1 Two Sum(查找)
Given an array of integers, find two numbers such that they add up to a specific target number. The ...
- UVA 10891 Game of Sum(DP)
This is a two player game. Initially there are n integer numbers in an array and players A and B get ...
随机推荐
- QTableWidget表头样式
转载请注明出处:http://www.cnblogs.com/dachen408/p/7742680.html QTableView { background-color: rgba(255, 255 ...
- COGS 2685. 迷妹
★ 输入文件:fans.in 输出文件:fans.out 简单对比时间限制:1 s 内存限制:256 MB [题目描述] 小钟.小皓和小曦都是著名偶像派OI选手,他们都有很多迷妹. 现 ...
- python的特殊数字类型(无穷大、无穷小等)
float('inf') 表示正无穷 -float('inf') 或 float('-inf') 表示负无穷 其中,inf 均可以写成 Inf 起步python中整型不用担心溢出,因为python理论 ...
- MFC_综述
第一天(win消息机制.SDK编程基础) 1.基本概念介绍(SDK.API.句柄.消息队列.winmain函数) 2.第一个Windows界面程序(winAPI) 3.消息循环和窗口 ...
- EBS ORACLE采购对账单自动产生发票
只要传入个对账单号,然后跑数据抛到接口表,运行接口请求,就可以自动生成发票 create or replace package body pkg_ap_check_by_po is --创建ap发票 ...
- 第1节 flume:9、flume的多个agent串联(级联)
3.两个agent级联 需求分析: 第一个agent负责收集文件当中的数据,通过网络发送到第二个agent当中去,第二个agent负责接收第一个agent发送的数据,并将数据保存到hdfs上面去 第一 ...
- xshell全局设置配色方案
新建XTerm1.xcs文件,将以下内容黏贴进去,保存退出 [XTerm] text=839496 cyan(bold)=93a1a1 text(bold)=408080 magenta=dd3682 ...
- 201621123079《java程序设计》第六周作业总结
作业06-接口.内部类 1. 本周学习总结 1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图或相关笔记,对面向对象思想进行一个总结. 2. 书面作业 1. c ...
- Ubuntu、CentOS 解决docker命令权限问题(sudo)
#创建docker组 weiyj@ubuntu18:~$ sudo groupadd docker groupadd: group 'docker' already exists #将当前用户加入do ...
- 条款30:透彻了解inline的里里外外(understand the ins and outs of inlining)
NOTE: 1.将大多数inline限制在小型 被频繁调用的函数身上.这可使日后的调试过程和二进制升级(binary upgradability)更容易,也可使潜在的代码膨胀问题最小化, 使程序的速度 ...