leetcode1. Two Sum
leetcode1.Two Sum
题意:
给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的值。
您可以假设每个输入都只有一个解决方案,而您不能使用相同的元素两次。
思路:
O(n),遍历,每次将当前的值和下标存入字典,遍历到结果时,target-当前值 应该在字典中,然后直接返回两者下标。
map的index为num[n],map的value为n
ac代码:
C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>res;
map<int,int> hash;
for(int i = 0; i < nums.size(); i++)
{
if(hash.find(target-nums[i])!=hash.end())
{
res.push_back(hash[target-nums[i]]);
res.push_back(i);
return res;
}
else
{
hash[nums[i]]=i;
}
}
return res;
}
};
python
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash = {}
for index,n in enumerate(nums):
if target - n in hash:
return [hash[target - n], index]
else:
hash[n] = index
return []