Two Sum

来源:互联网 发布:php class 内调用方法 编辑:程序博客网 时间:2024/04/30 09:01


题目: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


解析:

方法1:O(n^2) 先考察第一个元素,判断其后面的元素有没有与其和为target的,再判断第二个...以此类推,直到找到为止,最坏的情况是倒数第一个与倒数第二个和为target,此时共计算(比较):n-1 + n-2 + ... + 1,因此复杂度为O(n^2)。由于此方法无法通过LeetCode的在线评判,代码就不列了。


方法2:O(n) hash表,对数组{target-numbers[0],target-numbers[1],...,}构建,也就是说对target与每个元素的差为关键字构建一个散列表,值value为下标,然后再判断numbers中的元素是否在hash表中,由于hash表的查找复杂度为O(1),所以整个复杂度为O(n):

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> result;
     unordered_map<int,int> hmap;
     for(vector<int>::size_type i = 0;i<numbers.size();++i)
     {
         hmap[target - numbers[i]] = i;
     }
     for(vector<int>::size_type i = 0;i<numbers.size();++i)
     {
         if(hmap.count(numbers[i]) != 0 && hmap[numbers[i]] != i)//后面&&是排除自己与自己和为target的情况
         {
             int min = i;
             int max = hmap[numbers[i]];
             if(min > max) swap(min,max);
            
             result.push_back(min+1);
             result.push_back(max+1);
         }
     }
     return result;
    
    }
};

注意这里用的是unordered_map不是map,因为map的实现原理是RB-TREE,其查找为复杂度为O(lgn)而不是O(1);

0 0
原创粉丝点击