首页 > 代码库 > Two Sum(hashtable)

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=0;i<len;++i){            if (!m[numbers[i]])            {                m[numbers[i]]=i+1;            }else            {                if(numbers[i]+numbers[i]==target){                    res.push_back(m[numbers[i]]);                    res.push_back(i+1);                    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[0]>res[1])                    swap(res[0],res[1]);                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=0; 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+1);                    results.push_back(i+1);                    return results;                }            }        }        return results;    }};

 

Two Sum(hashtable)