数据结构与算法[LeetCode]—TwoSum

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


注意:题目并没有说明是给给定的numbers是有序的,并且测试数据也表明其实无序。


方法一:暴力搜索
     由于本题要求返回的是下标,所以不能够如同“3Sum”问题一样先排序,再二分查找使复杂度限制在O(nlogn)。只能进行暴力搜索O(n2)。
     当然用这种方法是要Time Limit Exceeded
     
class Solution{
public:
      vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> ret; 
        for(int i=0;i<numbers.size()-1;i++)
         {
             vector<int>::iterator iter;
             if((iter=find(numbers.begin()+i+1,numbers.end(),target-numbers[i]))!=numbers.end())
            {
                 ret.push_back(i+1);
                 ret.push_back(iter-numbers.begin()+1);  //迭代器转下标
                 return ret;
            }
                  
         }
         return ret;
      }

};



方法二:哈希法,将numbers中的数对应的下标存入哈希表。
复杂度为O(n)
class Solution{
public:
     vector<int> twoSum(vector<int> &numbers,int target){
         using namespace boost;
         vector<int>  ret;

         unordered_map<int,int> mapping;
         for(int i=0;i<numbers.size();++i){
             mapping[numbers[i]]=i;
         }

         for(int i=0;i<numbers.size()-1;++i)
         {
               int temp=target-numbers[i];
               if(mapping.find(temp)!=mapping.end() && mapping[temp]>i){
                 ret.push_back(i+1);
                 ret.push_back(mapping[temp]+1);
                 return ret;
                }
         }
         return ret;
     }
};

你可能感兴趣的:(数据结构与算法[LeetCode]—TwoSum)