原题:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。假设每一个输入肯定只有一个结果。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
}
};
使用两层循环可以完成,时间复杂度为o(n^2),空间复杂度为o(1),但是当输入的数组很大的时候,耗费的时间就会很长,所以需要改进代码。
此时考虑能够搜索的数据结构,考虑使用map,时间复杂度为O(n)。
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
map<int, int> m;
if (numbers.size() < 2)
return result;
for (int i = 0; i < numbers.size(); i++)
m[numbers[i]] = i;
map<int, int>::iterator it;
for (int i = 0; i < numbers.size(); i++) {
if ((it = m.find(target - numbers[i])) != m.end())
{
if (i == it->second) continue;
result.push_back(i+1);
result.push_back(it->second+1);
return result;
}
}
return result;
}
};