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].
给定一个数组和一个目标值,返回其两数之和等于目标值的索引,题目严格限定有唯一解。
最简单的想法就是两个循环,迭代查找出符合的解,时间复杂度为O(n),显然不符合算法之美。
另外一种方法是对数组进行排序,利用双指针从首尾逼近找出解。
最佳的方法是构建一个map,其中map的key存储数组的值,value存储数组的索引,在遍历数组的时候,在map中查找是否有target - num[i]的key,若没有则向map中添加当前的key、value,有的话即为所求解,map查找复杂度为O(logN),遍历一次,故总的复杂度为O(N*logN)。代码记录如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ret;
map<int, int> map_value;
for(int i = 0; i < nums.size(); i++)
{
if(map_value.find(target - nums[i]) == map_value.end())
map_value[nums[i]] = i;
else
{
ret.push_back(map_value[target - nums[i]]);
ret.push_back(i);
break;
}
}
return ret;
}
};