Question:
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].
分析:
法一:
要从一个数组里找两个元素的和等于目标值,简单的做法就是定义两个索引依次查找求和,等于目标值后存入数组返回即可。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>res(2);
for(int i=0; i<nums.size()-1; i++)
{
for(int j=i+1; j<nums.size(); j++)
{
if(nums[i]+nums[j] == target)
{
res[0] = i;
res[1] = j;
}
}
}
return res;
}
};
法二:
两个for循环时间复杂度达到O(n2),对于元素较多的数组效率极低,可以用哈希表来建立映射,对于nums中的每个元素,用其下标建立映射,遍历nums,如果target-nums[i]能在在map中找到对应的映射,且不与nums[i]在map中对应的映射相同,则就找到了这两个数,将下标依次存入res中即可。只用到一个for循环,时间复杂度为O(n)。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
vector<int>res;
unordered_map<int , int>m;
for(int i=0; i < len; i++)
m[nums[i]] = i;
for(int i=0; i < len; i++)
{
int t = target - nums[i];
if(m.count(t) && m[t] != i)
{
res.push_back(i);
res.push_back(m[t]);
break;
}
}
return res;
}
};