엔지니어 블로그
[LeetCode] 1. Two Sum 본문
풀이
기존에 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
'알고리즘' 카테고리의 다른 글
[Leetcode]2657. Find the Prefix Common Array of Two Arrays (0) | 2025.01.14 |
---|---|
[Leetcode] 916. Word Subsets (0) | 2025.01.10 |
[Leetcode]2006. Count Number of Pairs With Absolute Difference K (0) | 2025.01.04 |
[Leetcode]1941. Check if All Characters Have Equal Number of Occurrences (0) | 2025.01.04 |
[Leetcode]9.Palindrome Number (0) | 2025.01.01 |