标签:
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
其实思路很简单。将vector排序后维护两个指针(一头一尾),比较当前两个指针对应的数字的和和target,若小则向后移动头指针,若大向前移动尾指针。
代码如下。
vector<int> twoSum(vector<int> &numbers, int target) { int i, j, t; vector<int> answer; vector<int> old = numbers; // Sort the numbers. sort(numbers.begin(), numbers.end()); i = 0; j = numbers.size() - 1; while (i < j) { if (numbers[i] + numbers[j] == target) break; // If less than target, move i pointer to right. while (numbers[i] + numbers[j] < target) i++; // If greater than target, move j pointer to left. while (numbers[i] + numbers[j] > target) j--; } // Find original index of numbers[i] and numbers[j] for (t = 0; t < old.size(); t++) { if (old[t] == numbers[i]) { answer.push_back(t + 1); continue; } if (old[t] == numbers[j]) { answer.push_back(t + 1); continue; } if (answer.size() == 2) break; } sort(answer.begin(), answer.end()); return answer; }
其实运行结果倒还好。52ms运行时间。
只是最后查找原来下标的那部分代码有些丑,自己觉得不是很满意,但暂时也想不到太好的办法。
标签:
原文地址:http://www.cnblogs.com/aovaegis/p/4202420.html