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.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1, len(nums)):
plus = nums[i] + nums[j]
if plus == target:
return [i, j]
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
differences = {}
for index, number in enumerate(nums):
diff = target - number
if diff in differences:
return [index, differences[diff]]
else:
differences[number] = index
차(diff)
를 구한다. diff
라는 key가 dictionary에 있는 경우 현재 비교대상인 숫자의 인덱스와 key의 value(인덱스)를 반환한다.