[LeetCode][Python3]#1.Two Sum

Carvin·2020년 7월 25일
0

1. Two Sum

문제

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.

예시

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]

풀이

dic1 = {n : i for i, n in enumerate(nums)}
        for i, v in enumerate(map(lambda x : target - x, nums)):
            if v in dic1.keys():
                if i != dic1[v]:
                    return [i, dic1[v]]

input인 nums 리스트에서 두 원소의 합이 주어진 target을 만족하는 원소의 위치를 구하는 문제이다. 처음에 굉장히 어렵게 접근했지만 중복되는 원소가 딕셔너리의 키로 중복되어도 상관없다는 것을 깨달아서 코드를 수정하게 되었다.

다시 말하면, target에서 각 원소를 뺀 값이 input 원소에 존재하며, 같은 index가 아닐 때에 답을 구할 수 있게 된다. 즉, input이 [3, 2, 3] 일 때, target(6)에서 각 원소를 뺀 값은 [3, 4, 3] 인데 첫번째 인데스일 때는 반환해주면 안되기 때문이다.

결과

29 / 29 test cases passed.
Status: Accepted
Runtime: 40 ms
Memory Usage: 15.8 MB

0개의 댓글