1. Two Sum Python3

Yelim Kim·2021년 9월 15일
0
post-thumbnail

Problem

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.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

My code

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

Review

[실행 결과]
Runtime: 60 ms / Memory: 15.3MB

[접근법]
딕셔너리를 만든 다음, 하나의 숫자를 정해서 target에서 그 숫자를 뺀 숫자가 딕셔너리에 있는지 확인한다.
해당 루프의 key값(숫자 위치)과 뺀 숫자의 키값을 반환한다.

[느낀점]
처음에는 딕셔너리를 사용해서 예외에 집중하다 보니 이런 저런 if문이 잔뜩 많아졌다... 아무리 생각해도 이건 아닌 것 같아서 질질 끌다 새출발했다.
{3,3}일때 경우를 어떻게 처리할 지 모르겠어서 많이 난감했다. 마지막에는 해당 루프의 key값을 같이 반환하면 해결된다는 사실을 배웠다.
코드에서 사용할 수 있는 변수들을 이용하여 최대한 써먹자. 이상한거 새로운거 만들어내지 말자..

profile
뜬금없지만 세계여행이 꿈입니다.

0개의 댓글