Title Description: Given an array of integers, find the sum of two of them equals the target value, return two number of index values INDEX1 and INDEX2, guaranteed INDEX1<INDEX2, index value starting from 1.
For example: Input is numbers={2, 7, one, and target=9, output is index1=1, index2=2.
The most basic method is to traverse two numbers in two loops, with the following code:
1vector<int> Twosum (vector<int> &numbers,inttarget) {2vector<int>result;3 for(intI=0; I<numbers.size ()-1; i++)4 {5 for(intj=i+1; J<numbers.size (); j + +)6 {7 if(numbers[i]+numbers[j]==target)8 {9 Result.push_back (i+1);Ten Result.push_back (j+1); One returnresult; A } - } - } the}
After the submission of the decisive time Limit exceeded, in order to reduce the complexity, the array can be sorted first, and then adopt two pointers to the method: the head pointer and the tail pointer to add the index, larger than the target number is moving the tail pointer, less than the target number of moving the head pointer. Because to return the index value, we use the vector container that holds the pair<int,int> type to store the array value and the corresponding index. The code is as follows:
1vector<int> Twosum (vector<int> &numbers,inttarget) {2vector<int>result;3vector<pair<int,int> >mid;4 Mid.reserve (Numbers.size ());5vector<pair<int,int> >:: iterator pos;6vector<pair<int,int> >:: iterator end;7 for(intI=0; I<numbers.size (); i++)8 {9Mid.push_back (pair<int,int> (i+1, Numbers[i]));Ten } OneSort (Mid.begin (), Mid.end (), [&] (Constpair<int,int> &x,Constpair<int,int> &y)BOOL A { - returnX.second <Y.second; - }); the for(Pos=mid.begin (), End=mid.end ()-1;p os!=end;) - { - if((pos->second+end->second) = =target) - { + returnvector<int>( -{min (Pos->first, end->First ), +Max (Pos->first, end->First )}); A } at Else - { - if((Pos->second+end->second) >target) - { ---end; - } in Else - { to++Pos; + } - } the } *}
A simpler method, using the hash table method, use the hash table key to save the array value, use value to save the index, loop through the array, find out whether the current array value is in the hash table, not the target value minus the difference of the value as key, the loop I as value into the Hashtable, Otherwise, the value in the hash table corresponds to the value+1 and i+1 in the loop as the result.
To input for numbers={2, 7, one, and target=9 for example analysis, first hash table store no value, i=0, use the store in the Find method, did not find num[0], so store[9-2]=0;
Continue the loop, when I=1, use the Find method in store to find num[1], so the store corresponds to Value+1 and i+1 is the desired index value.
The code is as follows:
1vector<int> Twosum (vector<int>& Nums,inttarget) {2std::unordered_map<int,int>store;3 for(inti =0; I < nums.size (); ++i)4 {5Auto ITR =Store.find (Nums[i]);6 if(ITR! =store.end ())7 returnstd::vector<int> {itr->second+1, i+1}; 8 Else9Store[target-nums[i]] =i;Ten } One}
The Sum of