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 ...
随机推荐
- c++正则表达式模板库GRETA的使用
GRETA是微软研究院的一位前员工开发并开源的一个C++正则表达式库,兼容perl正则语法 官方介绍:“A fast, flexible, perl-compliant regular express ...
- Zend studio 修改编码格式
一.临时修改编码格式 edit -> Set Encoding... -> Other(选择) 二.修改软件默认编码格式
- .net MVC下跨域Ajax请求(JSONP)
一.JSONP(JSON with Padding) 客户端: <script type="text/javascript"> function TestJsonp() ...
- vux安装
1. 在项目里安装vux cnpm install vux --save 2. 安装vux-loader cnpm install vux-loader --save-dev 3. 安装less-lo ...
- 连接MySQL错误“plugin caching_sha2_password could not be loaded”的解决办法
MySQL新版默认使用caching_sha2_password作为身份验证插件,而旧版是使用mysql_native_password.当连接MySQL时报错“plugin caching_sha2 ...
- NodeJs运行服务器-day01
//读取内置模块http,这个模块开发服务器用的var http =require('http'); var server=http.createServer(function(req,res){ r ...
- Windows环境下安装 mysql-8.0.11-winx64 遇到的问题解决办法
下载mysql安装包,我的是下载mysql-8.0.11-winx64,解压到你想安装的目录下,然后配置环境(window环境下,mac本还没试过), 1.首先,配置环境:右击此电脑->属性-& ...
- reversing.kr easykeygen 之wp
补充: int(x,[base]): 就是将x(通常是一个字符串)按照base进制转换成整数. 比如: ’) ##转换成整数10 ) ##'按16进制转换,将得到整数16 ) ##得到255 int( ...
- 【HDU 2028】Lowest Common Multiple Plus
Problem Description 求n个数的最小公倍数. Input 输入包含多个测试实例,每个测试实例的开始是一个正整数n,然后是n个正整数. Output 为每组测试数据输出它们的最小公倍数 ...
- luogu3415 祭坛
先二分答案转化成判定问题. 考虑拿一根扫描线从 \(x=0\) 扫到 \(x=n\),每次移动扫描线更新每个位置它上面的点数和下面的点数,这样可以确定在当前的扫描线上哪些位置对于 \(y\) 轴方向是 ...