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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解决1:
利用两重循环查找,时间复杂度O(n*n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>result;
for(int i=0;i<nums.size()-1;i++)
for(int j=i+1;j<nums.size();j++)
{
if(nums[i]+nums[j]==target)
{
result.push_back(i);
result.push_back(j);
return result;
}
}
return result;//没有找到
}
};
解决2:
利用map容器,使用其find()成员函数,时间复杂度O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>result;
map<int,int>hash;
for(int i=0;i<nums.size();i++)
hash.insert({nums[i],i});
for(int i=0;i<nums.size();i++)
{
int dest = target-nums[i];
if(hash.find(dest)!=hash.end()&&hash[dest]!=i)//注意此处需要加hash[dest]!=i;例如(3,2,4 )6,而6-3 =3;此时,find后找到3,但是它的indices为0,与要求的不服;
{
result.push_back(i);
result.push_back(hash[dest]);
return result;
}
}
return result;//没有找到
}
};