letecode [167] - Two Sum II - Input array is sorted
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.
题目大意:
给定一个数组和目标值,找到数组中两数之和等于目标值。返回两数的下标(小在前)。
理 解:
方法一:遍历数组,利用map存放元素,若target-nums[i]在map中则找到这两个元素;否则将当期元素nums[i]放入map中。
方法二:双指针。首尾同时遍历数组,两数之和与目标值相比较。若小于目标值,则首指针后移;若大于目标值,则尾指针前移。
代 码 C++:
方法一:
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; } };
方法二:
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) i++; else { res.push_back(i+1); res.push_back(j+1); return res; } } return res; } };
运行结果:
方法一:执行用时 :12 ms, 在所有C++提交中击败了84.11%的用户
内存消耗 :9.7 MB, 在所有C++提交中击败了5.98%的用户
方法二:执行用时 :8 ms, 在所有C++提交中击败了95.64%的用户
内存消耗 :9.6 MB, 在所有C++提交中击败了16.03%的用户