问题描述:https://leetcode.com/problems/two-sum/
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
首先,根据题目给出的例子,大家一般都会想到利用两个头尾指针的方式进行运算。方法在于index1指向vector[0],index2指向vector[size()-1],然后计算Index1和index2所指的数值之和,如果和大于target,证明需要讲index2--,反之需要将index1++,如果想等,则直接返回index1和index2即可。
但是测试数据却不是完全有序的,刚开始我以为LeetCode并没有包含algorithm头文件,所以使用选择插入排序进行vector排序,时间复杂度为O(n2),提交之后超时了。后来才知道,原来LeetCode已经包含了algorithm头文件,所以该用sort函数完成vector的排序,时间复杂度为O(nlogn)。
由于题目要求输出的是原先列的索引,所以我们需要复制一个新的vector,对新的vector进行排序,在新的vector寻找和等于target的两个元素,然后在原先的vector中查找这两个元素,代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> tempv(nums);
sort(tempv.begin(), tempv.end());
int index1 = 0, index2 = tempv.size()-1;
while (tempv[index1]+tempv[index2]!=target)
{
if (tempv[index1] + tempv[index2] < target)
index1++;
else
index2--;
}
int start = tempv[index1], end = tempv[index2];
int i = 0;
while (nums[i] != start)
{
i++;
}
vector<int> rs;
start=i+1;
i = nums.size() - 1;
while (nums[i] != end)
i--;
end=i+1;
rs.push_back(start<end?start:end);
rs.push_back(start<end?end:start);
return rs;
}
};