Programming/LeetCode
[LeetCode] Two Sum
데이터현
2022. 2. 9. 17:33
https://leetcode.com/problems/two-sum/
Two Sum - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Leet Code의 문제들을 풀어 볼 예정이다.
처음 문제인 Two Sum 문제를 풀어봤다.
예전 화이트보드 코딩 테스트때 이 문제를 접한 적이 있었는데, 이렇게 유명한 문제인지 몰랐다.
그 때는 잘 못 풀었는데..
이 문제는 dict 를 사용하면 O(n) 으로 풀이할 수 있다.
나의 풀이
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_dict = {}
for i,num in enumerate(nums):
if (target-num) in num_dict:
return [num_dict[target-num],i]
else:
num_dict[num] = i