Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2.
Problem Solving Ideas:
Use target minus each number in the array to get the array of difference array, with the example in the original question: {2,7,11,15} corresponds to the difference array of {7,2,-1,,6}, and then traverse the original array, if the difference array also contains this number and the corresponding index is not equal, Returns the index of the original array in the value index and the array of difference values. In order to make the time complexity O (n), the difference data needs to be stored in the form of a hash map.
Problem Solving Source:
1 classSolution {2 Public:3vector<int> Twosum (vector<int>& Nums,inttarget) {4map<int,int>Finder;5 intIndex1 =-1;6 intIndex2 =-1;7 for(intI=0; I<nums.size (); ++i) {8 int_num = target-Nums[i];9Finder.insert (map<int,int>:: Value_type (_num, i));Ten } One for(intI=0; I<nums.size (); ++i) { Amap<int,int>:: iterator ITR; -ITR =Finder.find (Nums[i]); - if(itr!=Finder.end ()) { the intj =Finder[nums[i]]; - if(i!=j) { -Index1 =min (i, j); -Index2 =Max (I, j); + Break; - } + } A } atvector<int>rst; -Rst.push_back (index1+1); -Rst.push_back (index2+1); - returnrst; - } -};
Leetcode Brush title Record-two Sum