1. Two Sum
題目原文
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)
{
map<int, int> p1;
map<int, int>::iterator it;
vector<int> p2;
for (int i = 0; i < nums.size(); i++)
{
int complement = target - nums[i];
it = p1.find(complement);
if (it != p1.end())
{
p2.insert(p2.begin() + 0, p1.at(complement));
p2.insert(p2.begin() + 1, i);
return p2;
}
p1.insert(pair<int, int>(nums[i], i));
}
}
};
Last updated
Was this helpful?