2019년 5월 16일 목요일

[leetcode]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.

번역)

숫자배열이 하나 주어지고, 그중 2개의 숫자로 target을 만족하는 indices(index)를 반환하라.
반드시 하나의 답은 존재하며, 같은 요소끼리는 더하지 않는다.

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

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

문제접근

2개의 숫자만 사용을 하니
target - num1 = num2
num1과 num2의 index를 구하면 된다.
반드시 있다고 되어있고 중복은 허용하지 않는다 하니.

mapper를 하나 만들어서
target-num1의 값이 없다면 mapper에 넣어주고, mapper에 값이 있으면 반환해주면 된다.


소스코드


1
2
3
4
5
6
7
8
9
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        table = {}
        for i in range(len(nums)):
            num = target - nums[i]
            if table.get(num) is not None:
                return [table[num], i]
            else:
                table[nums[i]] = i

댓글 없음:

댓글 쓰기