[leetcode]two sum (遍历 哈希)
2015-09-09 15:04
786 查看
Two Sum
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
输入一段数字,给定一个目标和,求出一段数字中两个数字相加等于目标和,输出这两个数字所在的位置(左小有大)。
分析:遍历这段数组,正向读每一个数字时,看是否(和-数字)在数组中存在,输出 break
class Solution { 2 public: 3 vector<int> twoSum(vector<int> &numbers, int target) { 4 unordered_map<int, int> mp; 5 vector<int> ans; 6 for(int i = 0; i < numbers.size(); i ++) 7 { 8 if(mp.count(target - numbers[i])) 9 { 10 ans.push_back(mp[target - numbers[i]] + 1); 11 ans.push_back(i + 1); 12 break; 13 } 14 if(!mp.count(numbers[i])) mp[numbers[i]] = i; 15 } 16 return ans; 17 } 18 };
用哈希只遍历一遍数组,复杂度为o(n)。
Unordered Map
哈希map是一种关联容器,通过键值和映射值存储元素。允许根据键值快速检索各个元素。
在unordered_map中,键值一般用来唯一标识元素,而对应的值是一个对象关联到这个键的内容。键映射值的类型可能会有所不同。
在内部unordered_map的元素不以键值或映射的元素作任何特定的顺序排序,其存储位置取决于哈希值允许直接通过其键值为快速访问单个元素(具有恒定平均的平均时间复杂度)。
unordered_map容器比map容器更快地通过键值访问他们的单个元素,虽然unordered_map一般都是比map通过其元素的一个子集范围迭代效率低。
哈希map允许使用操作运算符(运算符[])以其键值作为参数直接访问元素。
相关文章推荐
- Developer-ScrollView
- 《程序员面试金典》--反转字符串
- 实现上拉刷新下拉加载的布局
- android L平台增加来电翻转静音菜单、功能
- poj 2229
- Effective Java 创建和销毁对象
- CentOS 6 下启动ORACLE 11gR2
- 详解CSS3特性@Media如何实现响应式设计
- ALM11需求和测试覆盖率图解1
- LinkedList 链表
- HTML/CSS(五)HTML5服务器推送事件
- 摄像机标定中用到的函数
- Hdu 1025 Constructing Roads In JGShining's Kingdom 最大上升子序列nlogn算法
- iOS图像拉伸解决方案
- myql_链接丢失异常_mybaits _等框架_报错_The last packet successfully
- Oracle语句优化之一
- ogg
- php-leveldb 扩展安装 和使用
- 反向传导算法
- 有用但多疑的十大Java编程技术