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].
Solution 1:
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
unordered_map<int, int> myMap;
vector<int> result; for(size_t i = ; i < nums.size(); ++i)
{
myMap[nums[i]] = i;
} for(size_t i = ; i < nums.size(); ++i)
{
const int gap = target - nums[i];
auto it = myMap.find(gap);
if(it != myMap.end() && it->second != i)
{
result.push_back(i);
result.push_back(myMap[gap]);
break; // Assume that each input would have
// exactly one solution
}
}
return result;
}
};
Solution 2: 暴力查找,超时
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> result;
for(size_t i = ; i < nums.size(); ++i)
{
for(size_t j = i + ; j < nums.size(); ++j)
{
if(nums[i] + nums[j] == target)
{
result.push_back(i);
result.push_back(j);
break;
}
}
}
return result;
}
};
Solution 3: 先排序,然后左右夹逼
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
vector<int> result;
vector<Node> num;
for(size_t i = ; i < nums.size(); ++i)
{
Node temp;
temp.value = nums[i];
temp.pos = i;
num.push_back(temp);
}
sort(num.begin(), num.end(), cmp);
for(size_t i = , j = num.size() - ; i != j; )
{
int sum = num[i].value + num[j].value;
if(sum == target)
{
int smallPos = min(num[i].pos, num[j].pos);
int largePos = max(num[i].pos, num[j].pos);
result.push_back(smallPos);
result.push_back(largePos);
break; // 找到解后,中断
}
else if(sum > target) --j;
else ++i;
}
return result;
}
private:
struct Node
{
int value;
int pos;
};
static bool cmp(const Node &a, const Node &b)
{
return a.value < b.value;
}
};