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
[Thoughts] 两种解法。 解法一, hash 从左往右扫描一遍,然后将数及坐标,存到map中。然后再扫描一遍即可。时间复杂度O(n) 解法二,双指针扫描 将数组排序,然后双指针从前后往中间扫描。时间复杂度O(n*lgn)。因为是要求返回原数组的下标,所以在排序的时候还得有额外的数组来存储下标信息, 也挺麻烦。 解法三,暴力搜索 这个倒是最省事的。时间复杂度O(n*n) 解法一实现如下: 1: vector twoSum(vector &numbers, int target) { 2: map解法二mapping; 3: vector result; 4: for(int i =0; i< numbers.size(); i++) 5: { 6: mapping[numbers[i]]=i; 7: } 8: for(int i =0; i< numbers.size(); i++) 9: { 10: int searched = target - numbers[i]; 11: if(mapping.find(searched) != mapping.end()) 12: { 13: result.push_back(i+1); 14: result.push_back(mapping[searched]+1); 15: break; 16: } 17: } 18: return result; 19: }
1: struct Node 2: { 3: int val; 4: int index; 5: Node(int pVal, int pIndex):val(pVal), index(pIndex){} 6: }; 7: static bool compare(const Node &left, const Node &right) 8: { 9: return left.val < right.val; 10: } 11: vector twoSum(vector &numbers, int target) { 12: vector解法三,两个循环嵌套搜索,不写了。elements; 13: for(int i =0; i< numbers.size(); i++) 14: { 15: elements.push_back(Node(numbers[i], i)); 16: } 17: std::sort(elements.begin(), elements.end(), compare); 18: int start = 0, end = numbers.size()-1; 19: vector result; 20: while(start < end) 21: { 22: int sum = elements[start].val + elements[end].val; 23: if(sum == target) 24: { 25: result.push_back(elements[start].index+1); 26: if(elements[start].index < elements[end].index) 27: result.push_back(elements[end].index+1); 28: else 29: result.insert(result.begin(),elements[end].index+1); 30: break; 31: } 32: else if(sum > target) 33: end--; 34: else 35: start++; 36: } 37: return result; 38: }