Given an array of integers, 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. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15},
target=9
Output: index1=1,
index2=2
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int> &numbers, int target) { 4 unordered_map<int, int> mapping;//hash talbe 5 vector<int> result; 6 for(int i = 0; i < numbers.size(); i ++) 7 { 8 mapping[numbers[i]] = i;//hash,store every number‘s index-1 9 } 10 for(int i = 0; i < numbers.size(); i ++) 11 { 12 const int gap = target - numbers[i]; 13 if(mapping.find(gap) != mapping.end()) 14 { 15 if(i == mapping[gap]) continue; //attention:index1 < index2, cant‘t equal. 16 result.push_back(i + 1); 17 result.push_back(mapping[gap] + 1); 18 break; 19 } 20 } 21 return result; 22 } 23 };
代码参考自https://github.com/soulmachine/leetcode
LeetCode Two Sum,布布扣,bubuko.com
原文:http://www.cnblogs.com/heiqiaoxiang/p/3691880.html