In the Leetcode Two Sum problem solution in Python programming Given an array of integer nums and an integer target, return indices of the two numbers such that they add up to the target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Leetcode Two Sum problem solution in Python programming
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
answer = []
for x in range(len(nums)):
if d:
check = target - nums[x]
if(check in d):
answer.append(d.get(check))
answer.append(x)
return answer
else:
d[nums[x]] = x
else:
d[nums[x]] = x
return answer
Also read,
- Leetcode Two Sum Problem Solution in C
- Leetcode Two Sum Problem Solution in C++
- Leetcode Two Sum Problem Solution in Java
- Leetcode two Sum Problem Solution in C#