LeetCode - 1. Two Sum (Python)

조민수·2024년 6월 2일
0

LeetCode

목록 보기
3/61

Easy, Python - List

RunTime : 1667 ms / Memory : 17.2 MB


문제

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.


풀이

  • 1667 ms 의 풀이, 단순하게 생각했다.
  • 너무 느린 면이 없지 않아 있다.
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        res = []
        for i in range(len(nums) - 1):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    res = [i, j]
                    return res
  • RunTime 45 ms 의 미친 풀이
  • 딕셔너리를 통해 해당 값에 대한 idx를 저장해 차이값을 확인하며 이를 가져온다.
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        buf = {}

        for index, num in enumerate(nums):
            diff = target - num
            if diff in buf:
                return [index, buf[diff]]
            if num not in buf:
                buf[num] = index
profile
사람을 좋아하는 Front-End 개발자

0개의 댓글