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 vector<int> result; 5 unordered_map<int, int> mapping; 6 for (size_t i = 0; i < numbers.size(); ++i) { 7 mapping[numbers[i]] = i; 8 } 9 for (size_t i = 0; i < numbers.size(); ++i) { 10 int t = target - numbers[i]; 11 if (mapping.find(t) != mapping.end() && mapping[t] != i) { 12 result.push_back(i + 1); 13 result.push_back(mapping[t] + 1); 14 break; 15 } 16 } 17 return result; 18 } 19 };
暴力O(n2)超时,由于要求输出的是下标,所以不能排序,利用hash。
另外题目没有说明的是:要求输出的两个下标是不同的。例如{3, 2, 4} target = 6 应该输出 2,3 而不是1,1.