Title:
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, target=9
Output: index1=1, index2=2
Tips:
This problem is very common, there are usually two kinds of solutions, one is to use a hash table, its time complexity is O (n), the other is to sort the array, the time complexity is O (NLOGN). But the actual execution is less time consuming than the second. So sometimes when the data size is small, the coefficient is also a key factor.
Code:
Hash Table Method:
classSolution { Public: Vector<int> Twosum (vector<int>& Nums,inttarget) {Unordered_map<int,int>map; intn = (int) nums.size (); for(inti =0; I < n; i++) {Auto P= Map.find (target-Nums[i]); if(p!=Map.end ()) { return{p->second+1, i+1}; } Map[nums[i]]=i; } }};
Sort by:
classsolution{ Public: Vector<int> Twosum (vector<int>& numbers,inttarget) {Vector<int>tmpnumbers (Numbers.begin (), Numbers.end ()); Sort (Tmpnumbers.begin (), Tmpnumbers.end ()); intVal1 =-1; intVal2 =-1; inti =0; intj = tmpnumbers.size ()-1; while(I <j) {if(Tmpnumbers[i] + tmpnumbers[j] < target) + +i; Else if(Tmpnumbers[i] + tmpnumbers[j] > target)--J; Else{val1=Tmpnumbers[i]; Val2=Tmpnumbers[j]; Break; }} vector<int>result; for(inti =0; I < numbers.size (); ++i) {if(Numbers[i] = = Val1 | | numbers[i] = = val2) Result.push_back (i +1); if(2= = Result.size ())returnresult; } returnresult; }};
"Leetcode" 2. The Sum of