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
最开始我很自然地想先排序,然后用两根指针来遍历数组,后来发现这道题要求返回的是坐标。所以常规的排序就不行了。于是这里巧妙地用了一下指针。排序的时候,我们并不对数组的元素排序,而是对指针排序。具体代码见下面,这里自己定义了一个新的比较直真的函数cmp,比较指针指向的元素。同时又可以保留指针信息。
class Solution {
private:
static bool cmp(vector<int>::iterator a,vector<int>::iterator b) {
return *a<*b;
}
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
vector<vector<int>::iterator> iter;
for (int i = 0; i < nums.size(); i++) {
iter.push_back(nums.begin()+i);
}
sort(iter.begin(),iter.end(),cmp);
int left = 0, right = iter.size()-1;
while (left < right) {
if (*iter[left] + *iter[right] == target) {
result.push_back(iter[left]-nums.begin()+1);
result.push_back(iter[right]-nums.begin()+1);
sort(result.begin(),result.end());
return result;
}
if (*iter[left] + *iter[right] < target)
left++;
if (*iter[left] + *iter[right] > target)
right--;
}
return result;
}
};