原题
原题地址
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
翻译
给定一个数组,返回两个数字的下标索引,使它们相加到特定值。
你可以认为输入的每个测试用例只有一个特定解且数组中没有值相同的元素。
示例:
数组 nums=[2, 7, 11, 15],目标target=9,
因为nums[0] + nums[1] = 2 + 7 = 9,
返回[0,1].
分析
直接用BF(Brute Force)暴力求解就是通过两层循环嵌套完成,时间复杂度O(n2),会超时,不是一个很好的方法,此处不再赘述。
第二种方法就是以时间换空间,把数组存到一个map里面,map的key为数组的值,map的value为数组的下标。这样只需要遍历原数组,查看a=target-nums[i]的值在不在map的下标中,如果存在且map[a]与i不相等,则这两个值就是需要返回的下标。
时间复杂度O(n),空间复杂度O(n)。
代码如下:
代码(C++)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> Myset;
vector<int> results;
for (auto tmp = nums.begin(); tmp<nums.end(); tmp++) Myset[*tmp] = tmp - nums.begin();
for (auto tmp = Myset.begin(); tmp != Myset.end(); tmp++) cout << (*tmp).first << " "<< (*tmp).second<<endl;
for (auto tmp = nums.begin(); tmp < nums.end(); tmp++)
{
if (Myset.find(target - *tmp) != Myset.end()&& (*Myset.find(target - *tmp)).second!=(tmp - nums.begin()))
{
results.push_back(tmp - nums.begin());
results.push_back(Myset[target - *tmp]);
break;
}
}
return results;
}
};