原題鏈接: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].
C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int, int> temp_map;
std::vector<int> res;
for(int i = 0; i < nums.size(); i ++)
{
if(temp_map.count(target - nums[i]))
{
res.push_back(temp_map[target - nums[i]]);
res.push_back(i);
break;
}
if(temp_map.count(nums[i]) != 1)
{
temp_map[nums[i]] = i;
}
}
return res;
}
};
Python
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
res = dict()
for i in range(0, len(nums)):
if res.get(target - nums[i], None) == None:
res[nums[i]] = i
else:
return (res[target - nums[i]], i)