엔지니어 블로그
[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
재풀이
다시 풀어보니 다른 방식으로 문제 풀이가 되어서 추가로 글을 써본다. 이전에 hash를 사용해서 값들을 저장하는 방식으로 풀었다면 이번엔 for문을 적극 활용한다. 조금은 무식한 방식이지만 나름 직관적이다.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
i = 0
num = 1
while i < len(nums):
for j in range(num,len(nums)):
if (target - nums[i]) == nums[j]:
return [i,j]
i += 1
num += 1
'알고리즘' 카테고리의 다른 글
[Leetcode] 20. Valid Parentheses (0) | 2025.02.20 |
---|---|
[Leetcode] 392.Is Subsequence (0) | 2025.02.12 |
[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 |