《LeetBook》LeetCode题解(1) : Two Sum[E]——哈希Map的应用
001.Two Sum[E]
1.题目
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
2.思路
2.1双重循环
最简单的思路,两重循环,没啥技术含量,速度很慢,毕竟是O(N2)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i = 0;i < nums.size();i++)
{
for(int j = i+1;j < nums.size();j++)
if(nums[i] + nums[j] == target)
{
result.push_back(i);
result.push_back(j);
return result;
}
}
}
};
2.2 排序
其实简单的想,用一个排序都能把复杂度降到O(NlogN),通过排序,然后用两个指针从前后扫描逼近真值,因为一定会有一个值满足,然后通过值去原数组里找对应的下标(这里其实就可以考虑,如果当初就用一个数据结构存好键值对应关系就好了,其实就是hashmap,下面的做法就用到了)
(下面代码是 dugu9sword写的java代码,我就没写成c++的,主要看思路,还是比较好理解的)
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] nums_sorted=new int[nums.length];
System.arraycopy(nums,0,nums_sorted,0,nums.length);
//Quicksort.
Arrays.sort(nums_sorted);
//Find the two numbers. O(n)
int start=0;
int end=nums_sorted.length;
while(start<end){
while(nums_sorted[start]+nums_sorted[--end]>target);
if(nums_sorted[end]+nums_sorted[start]==target)
break;
while(nums_sorted[++start]+nums_sorted[end]<target);
if(nums_sorted[end]+nums_sorted[start]==target)
break;
}
//find the indices of the two numbers
int[] ret=new int[2];
int index=0;
int a=nums_sorted[start];
int b=nums_sorted[end];
for(int i=0;i<nums.length;i++)
if(nums[i]==a || nums[i]==b)
ret[index++]=i;
return ret;
}
}
2.3 Hashmap
最后一种是比较聪明的做法,用hashmap,hashmap是内部存储方式为哈希表的map结构,哈希表可以达到查找O(1),哈希表的介绍可以看这里, C++实现Hashmap的方式,这里用unordered_map关联容器,可以实现键值对应。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
unordered_map<int,int> mymap;
int res;
for(int i = 0;i < nums.size();i++)
{
res = target - nums[i];
unordered_map<int,int>::iterator it = mymap.find(res);
if(it != mymap.end())
{
return vector<int>({it->second,i});
}
mymap[nums[i]] = i;
}
}
};
《LeetBook》LeetCode题解(1) : Two Sum[E]——哈希Map的应用的更多相关文章
- [LeetCode 题解]:Path Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given a bi ...
- LeetCode题解39.Combination Sum
39. Combination Sum Given a set of candidate numbers (C) (without duplicates) and a target number (T ...
- LeetCode题解 #1 Two Sum
在LeetCode做的第一到题 题目大意:给出n个数,在其中找出和为一个特定数的两个数. Input: numbers={2, 7, 11, 15}, target=9Output: index1=1 ...
- LeetCode 题解之 Two Sum
1.题目描述 2.问题分析 使用hashTable 寻找,target - num[i] ,将时间复杂度降低到 O(n): 3.代码 vector<int> twoSum(vector ...
- LeetCode题解之 two sum 问题
1.题目描述 2.题目分析 考虑使用hashMap的方式将数组中的每个元素和下表对应存储起来,然后遍历数组,计算target 和 数组中每个元素的差值,在hashMap中寻找,一直到找到最后一对. 3 ...
- [LeetCode题解]160. 相交链表 | 双指针 + 哈希表
方法一:双指针 解题思路 假设链表存在相交时,headA 的长度为 a + c,headB 的长度为 b + c.如果把 headA 连上 headB,headB 连上 headB 的话,当遍历这两个 ...
- Leetcode No.1 Two Sum(c++哈希表实现)
1. 题目 1.1 英文题目 Given an array of integers nums and an integer target, return indices of the two numb ...
- [LeetCode 题解] Combination Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given a se ...
- [LeetCode 题解]: Two Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given an a ...
随机推荐
- 修改VS中的附加依赖项的继承值
工程用不到的库,想去都去不掉,一直链接错误... 解决方法:打开vs的“属性管理器”窗口.通过这个窗口就可以对里面的继承值进行编辑了 另,“属性管理器”这个窗口,一般在“其他窗口”选项里(至少VS20 ...
- selenium 元素可以定位到,但是无法点击问题
报错1: selenium.common.exceptions.WebDriverException: Message: Element is not clickable at point (82, ...
- Android应用安全解决方案
Apk安全解决方案 背景 公司为政府做的App开发完了,需要上一些手段保证安全.这样客户才放心嘛. 防止第三方反编译篡改应用,防止数据隐私泄露,防止二次打包欺骗用户. 目录 Apk安全解决方案 背景 ...
- 关于EF的一点小记录
今日新闻:朝鲜要改革开放了!!!比你牛逼的人都在努力,你还有理由懒惰吗? 宇宙强大IDE配套的EF问题记录 今天做数据添加时,Id我设置为int类型了,结果在做Add操作时报的错让我摸不着头脑,后来问 ...
- ceph luminous 新功能之内置 dashboard
# 开启 dashboard (在任一 mon_server 节点上)ceph mgr module enable dashboard # 设置dashboard 端口和IPceph config-k ...
- zTree第三章,异步加载,前端
zTree异步加载 ---------------------------------------------------------------------------------- 具体详见API ...
- Python 用队列实现多线程并发
# Python queue队列,实现并发,在网站多线程推荐最后也一个例子,比这货简单,但是不够规范 # encoding: utf-8 __author__ = 'yeayee.com' # 由本站 ...
- Python装饰器(函数)
闭包 1.作用域L_E_G_B(局部.内嵌.全局...): x=10#全局 def f(): a=5 #嵌套作用域 def inner(): count = 7 #局部变量 print a retur ...
- PHP中利用Redis管道加快执行
$redis->muti($mode)->get($key)->set($key)->exec(): 既然是这样的, 也就是说当我要使用管道执行一万次操作的时候需要写一万次操作 ...
- [译文]casperjs的API-mouse模块
mouse类 这个类是对各种鼠标操作的抽象,比如移动,点击,双击,滚动等.它要求一个已经获得DOM属性的casper对象,能用这种方式创造一个鼠标对象: var casper = require(&q ...