본문 바로가기
LeetCode/Top Interview Q. - Easy

LeetCode 01. Two Sum

by 벤진[Benzene] 2020. 5. 21.

Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

 

Example:

Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

 

Summary:

1. nums list를 돌며 target-num을 하였을때 다른 number가 dict 안에 있는지 확인.

2. 확인되면 그 숫자의 index 번호와 다른숫자의 index번호를 list안에 넣어 return.

3. 없을경우에는 그 숫자의 뺀값을 키로 넣어주고, value는 enumerate function의 index 값을 넣어줌.

 

ex) [2,7,11,15]

1) check if 2 is already in a dic. --> not exist 

dict --> {7:0}

2) check if 7 is already in a dic. --> Exist

--> return [0,1] 

 

아래와 같은 반대방법으로도 가능.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        
        for i, n in enumerate(nums):
            if target-n in dic:
                return [dic[target-n],i]
            else:
                dic[n] = i

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

https://leetcode.com/

 

'LeetCode > Top Interview Q. - Easy' 카테고리의 다른 글

LeetCode 48. Rotate Image  (0) 2020.05.22
LeetCode 283. Move Zeroes  (0) 2020.05.22
LeetCode 189. Rotate Array  (0) 2020.05.22
LeetCode 36. Valid Sudoku [Medium]  (2) 2020.05.20
LeetCode 344. Reverse String [Easy]  (0) 2020.05.20

댓글