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=9Output: index1=1, index2=2
思路:
排序后两个指针一个从前往后,一个从后往前逼近。需要小心的是当输入数组可有重复的数字,所以需要先保存每个数字在哪些位置出现过以备查询。
1 class Solution { 2 public: 3 vector twoSum(vector &numbers, int target) { 4 vector result; 5 map
> indexes; 6 int i, j, size = numbers.size(); 7 8 for (i = 0; i < size; ++i) { 9 indexes[numbers[i]].push_back(i + 1);10 }11 12 sort(numbers.begin(), numbers.end());13 i = 0; 14 j = size - 1;15 16 while (i < j) {17 if ((numbers[i] + numbers[j]) < target) {18 ++i;19 }20 else if ((numbers[i] + numbers[j]) > target) {21 --j;22 }23 else {24 vector
::iterator left = indexes[numbers[i]].begin();25 vector
::iterator right = indexes[numbers[j]].begin();26 27 if (left == right) {28 ++right;29 }30 31 result.push_back((*left < *right) ? *left : *right);32 result.push_back((*left < *right) ? *right : *left);33 34 break;35 }36 }37 38 return result;39 }40 };