[leetcode]two sum (遍历 哈希)

来源:互联网 发布:大数据图片 编辑:程序博客网 时间:2024/05/16 17:40

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允许使用操作运算符(运算符[])以其键值作为参数直接访问元素。

0 0
原创粉丝点击