link:https://oj.leetcode.com/problems/two-sum/
Given an array of integers, find two numbers such this they add up to a specific target number.
The function twosum should return indices of the two numbers such this they add up to the target where index1 must is Les S than Index2. Please note this your returned answers (both INDEX1 and index2) are not zero-based.
You may assume this each input would have exactly one solution.
Input:numbers={2, 7, one, target=9
Output:index1=1, index2=2
Required for the given array to find two numbers added to the specified number, the given group has only one set of the correct combination of the given value, the location of both values (not 0 start)
Train of thought: Because the answer is unique, each two value 22 can be added.
1 sort the array, pointing to the two digits
After 22 digits are added, if greater than the given value, a reduced process is required, the trailing position is 1, the amount of the sum is reduced, and the amount is increased if the head position is less than the given value.
3 Repeat the 2nd step, always get the sum equal to the given value of the two digits, note that the position, not the value.
Because the process needs sorting, you need to copy the array to save the location of the original array.
When the original array position is evaluated by value, note that if the two values that are calculated are the same, they will get two identical positions:
[3,4,1,4,9,2,10], 8, sorted as [1,2,3,4,4,9,10], from 4, 4 get 4 positions, will take a different two position for the answer
Class Solution {public
:
vector<int> twosum (vector<int> &numbers, int target) {
vector <int> nums = numbers; Copy the array to save the original location
sort (Nums.begin (), Nums.end ());
int beg = 0, end = Nums.size ()-1;
Vector<int> re;
for (;beg<end;)
{ if (nums[beg]+nums[end]> target) {
--end
}
else if (nums[beg]+nums[end]< target) {
++beg
}
else
{ for (unsigned long i=0; i<numbers.size (); i++) { //position into stack, if [beg]==[end], get 4 locations if
( Numbers[i]==nums[beg])
re.push_back (i+1);
if (Numbers[i]==nums[end])
re.push_back (i+1);
}
if (Re.size () >2) {
re[1]=re[2]; 4 positions, swap the same value
} return
re;}
return re;
}
;