엔지니어 블로그

[LeetCode] 1. Two Sum 본문

알고리즘

[LeetCode] 1. Two Sum

안기용 2025. 2. 1. 21:16


풀이

기존에 for문을 중첩해서 사용하는 방법으로 문제를 풀었다. 정답은 됐지만 상당히 속도가 느린 정답이 되어 효율적인 방법을 고민해보았고, hash table을 사용하여 새롭게 문제를 풀었다. 물론 아이디어는 떠올려냈지만 구현은 솔루션을 살-짝 컨닝했다 ㅎ

 

코드

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