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 ...
随机推荐
- pip和pip3安装、升级、版本查看及遇到的问题
pip的安装 问题一 sudo apt-get install python-pip #安装pip sudo pip install --upgrade pip -i http://mirrors.a ...
- execl, execlp, execle, execv, execvp - 执行某个文件
总览 (SYNOPSIS) #include <unistd.h> extern char **environ; int execl( const char *path, const ch ...
- ignore-on-commit svn 更改文件后 默认不提交文件到服务器(服务器上已存在的文件)
不用那个忽略文件那个,那个功能是删除服务器的文件,然后本地还存在,不符合我的要求 我的要求是 服务器文件在,我不动,然后我改完了,和别人的不冲突,我也不覆盖别人的文件 主要就是默认不提交,这个很重要 ...
- CSS继承inherit | elementUI NavMenu vertical竖版 加 A标记 外联 不能继承上层color,需要手写下color:inherit;
<li data-v-576b9cf5="" role="menuitem" tabindex="0" class="el- ...
- Java数据结构和算法(四)--链表
日常开发中,数组和集合使用的很多,而数组的无序插入和删除效率都是偏低的,这点在学习ArrayList源码的时候就知道了,因为需要把要 插入索引后面的所以元素全部后移一位. 而本文会详细讲解链表,可以解 ...
- 通俗理解 模糊自适应PID
模糊自适应PID算法就是在经典的PID的基础上添加模糊控制规则库,建立这个库的目的就是算法能够自己来进行改变P.I.D的值. 就拿温度的上升过程控制来说,刚开始的时候,希望温度能够快速的升到终点温度, ...
- 区间DP || HDU 6249 Alice’s Stamps
题意:标号为1-n的n种邮票,m个邮票集,每个集里有标号从Li到Ri的邮票,要从中选K个邮票集,使这K个邮票集能覆盖最多种的邮票,问最多能覆盖多少种邮票 思路:区间DP (我:??? f[i][j]表 ...
- Linux配置ssh免密登录
假定有3台机,用户名和IP分别是:C1 192.168.1.101C2 192.168.1.102C3 192.168.1.103 # 登入root用户su # 安装vimapt-get ins ...
- 【mybatis】mybatis数据源源码剖析(JNDI、POOLED、UNPOOLED)
一.概述 二.创建 mybatis数据源的创建过程稍微有些曲折. 1. 数据源的创建过程: 2. mybatis支持哪些数据源,也就是dataSource标签的type属性可以写哪些合法的参数? 弄清 ...
- css 给div 添加滚动条样式hover 效果
css .nui-scroll { margin-left: 100px; border: 1px solid #000; width: 200px; height: 100px; ...