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
Test Instructionsfind two numbers from an array so that the sum of these two numbers equals the given number of targets. Returns the position of these two numbers in the array
Ideas
1. Copy the original array in temp and sort
2. Start scanning from the head and tail of the sorted array: If Head+tail<target, then head++, then scan;
If Head+tail>target, then tail--, then scan; until Head+tail=target.
3. Find Temp[head] and Temp[tail] from the original array.
1Runtime: -Ms2 classSolution {3 Public:4vector<int> Twosum (vector<int>& Nums,inttarget) {5vector<int> temp =nums;6 sort (Temp.begin (), Temp.end ());7 intHead =0;8 inttail = temp.size ()-1;9 while(Temp[head]+temp[tail]! =target)Ten { One if(Temp[head]+temp[tail] >target) Atail--; - Else -head++; the } -vector<int> Array (2,0); - for(intI=0; I<temp.size (); i++) - { + if(Nums[i] = = Temp[head] | | nums[i] = =Temp[tail]) - if(array[0] ==0) +array[0] = i+1; A Else atarray[1] = i+1; - } - returnArray; - } -};
leetcode.001 the Sum