首页 > 代码库 > [leetcode] Two Sum

[leetcode] Two Sum

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

思路:

最笨的办法,确定第一个数,第二个数在数组遍历中寻找。时间复杂度有点高,估计会超时。

线性的办法是用哈希表的思路,确定第一个数字,第二个数字在哈希表中寻找。哈希表从循环开始逐渐建立。确定第一个数a1,那么第二个数a2=target-a1。如果哈希表中没有这个数,那就把第a1插入到哈希表中(这里注意不是插入a2,开始就sb的在那纠结这个问题)。这样逐渐遍历容器,哈希表也会逐渐插入元素,最终可以找到容器内的一个数与哈希表中的某个元素之和等于目标值,这两个数中,容器内的值下标比较大,哈希表中的值下标较小。

开始是用map做的,后来想想可能unordered_map性能应该更好,就把map换成了unordered_map,发现速度有一丝丝的提高。

题解:

技术分享
class Solution {public:    typedef unordered_map<int, int> HashTable;    vector<int> twoSum(vector<int> &numbers, int target) {        HashTable hash;        HashTable::iterator it;        vector<int> res;        for(int i=0;i<numbers.size();i++) {            int dif = target-numbers[i];            if((it=hash.find(dif))!=hash.end()) {                res.push_back(it->second);                res.push_back(i+1);            }            else                hash[numbers[i]] = i+1;        }        return res;    }};
View Code

 

[leetcode] Two Sum