Title Description
Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.
You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.
Example:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
solution
(1)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {}
for index, num in enumerate(nums):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num], index]
hashmap[num] = index
return None
(2)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for index_a, a in enumerate(nums):
for index_b, b in enumerate(nums):
ans = []
if index_a == index_b:
continue
if a + b == target:
ans.append(index_a)
ans.append(index_b)
return ans
else:
continue