Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
Subject to the effect :
Given an array and the target, find an array of two numbers is equal to the target value. Returns the index of the number of two (small forward).
Understanding:
Method a: to iterate, using a map storage element, if the target-nums [i] is found in both the map elements; otherwise profit element nums [i] into the map.
Method two: the double pointer. Meanwhile iterate inclusive, and the sum of two numbers is compared with a target value. If less than the target, then the pointer after the first shift; if larger than the target, then the tail pointer forward.
Code C ++:
method one:
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int n = numbers.size(); int i; map<int,int> m; vector<int> res; map<int,int>::iterator it; for(i=0;i<n;++i){ if(target>0 && numbers[i]>target) break; it = m.find(target-numbers[i]); if(it!=m.end()){ res.push_back(it->second+1); res.push_back(i+1); return res; } m.insert(pair(numbers[i],i)); } return res; } };
Method Two:
class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int n = numbers.size(); int i=0,j=n-1; vector<int> res; while(i<j){ if(numbers[i]+numbers[j]>target) j--; else if(numbers[i]+numbers[j]<target) in ++ ; else { res.push_back(i+1); res.push_back(j+1); return res; } } return res; } };
operation result:
Method One: When execution: 12 ms, beat the 84.11% of all users to submit in C ++