[Leetcode] Two sum

valas·2021년 9월 11일
0

Leetcode 문제풀이

목록 보기
1/2

링크

https://leetcode.com/problems/two-sum/

문제

Given an array of integers nums and and integer target, return the 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.

2개의 nums 엘레멘트의 합으로 target 값을 만들기

제약조건

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

고민&해결

target 값에서 한 엘레멘트를 빼고, 뺀 값이 nums배열에 있으면 된다

코드

class Solution: 
    def twoSum(self, nums: List[int], target: int) -> List[int]: 
        ret = [] 
        for i, num in enumerate(nums): 
            n = target - num 
            if n in nums: 
                idx = nums.index(n) 
                if i != idx: 
                    ret.append(i) 
                    ret.append(idx) 
                    break 

        return ret 

풀이 링크

https://leetcode.com/submissions/detail/389771116/

구루의 코드

0개의 댓글