给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
C++:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> buf;
vector<int> ans;
int len=nums.size();
for(int i=0;i<len;++i)
{
if(buf.count(nums[i]))
{
ans.push_back(buf[nums[i]]);
ans.push_back(i);
return ans;
}
buf.insert(make_pair(target-nums[i],i));
}
return ans;
}
};
Java:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
int len=nums.length;
for(int i=0;i<len;++i)
{
int complement=target-nums[i];
if(map.containsKey(complement)) return new int[] { map.get(complement), i};
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
Python3:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i,m in enumerate(nums):
if dic.get(m) is not None:
return [dic.get(m),i]
dic[target-m]=i;