Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to 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.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
res = []
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
res = [i, j]
return res
idx
를 저장해 차이값을 확인하며 이를 가져온다.class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
buf = {}
for index, num in enumerate(nums):
diff = target - num
if diff in buf:
return [index, buf[diff]]
if num not in buf:
buf[num] = index