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; } };
运行结果:
执行用时 :12 ms, 在所有C++提交中击败了84.11%的用户
内存消耗 :9.7 MB, 在所有C++提交中击败了5.98%的用户标签:map,return,target,res,Sum,Two,letecode,vector,numbers 来源: https://www.cnblogs.com/lpomeloz/p/11002953.html