Skip to content

Commit 87ba189

Browse files
committed
add two-sum solution
1 parent 151a0f1 commit 87ba189

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

two-sum/jongwanra.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
[Problem]
3+
https://leetcode.com/problems/two-sum/description/
4+
5+
nums.length <= 10^4 => 10,000 * 10,000 => n^2 time complexity일 경우 1초 이상 소요
6+
7+
[Plan]
8+
nums를 hash table로 만들자. (key: element, value: index)
9+
이후에 nums를 돌면서 target - current_num을 뺀 값이 hash table에 존재한 경우 return하자.
10+
그랬을 경우, O(n) 시간 복잡도를 예상한다.
11+
12+
[Complexity]
13+
N: nums length
14+
Time: O(N) => HashTable에 nums를 만큼 반복문 돌림
15+
Space: O(N) => nums length 만큼 반복문을 돌면서 hash table을 생성
16+
"""
17+
18+
class Solution(object):
19+
def twoSum(self, nums, target):
20+
num_to_index_map = dict()
21+
for index in range(len(nums)):
22+
num_to_index_map[nums[index]] = index
23+
24+
for index in range(len(nums)):
25+
num = nums[index]
26+
diff = target - num
27+
# target - num 값이 존재 하지 않을 경우 무시
28+
if not diff in num_to_index_map:
29+
continue
30+
# index가 자기 자신인 경우 무시
31+
if index == num_to_index_map[diff]:
32+
continue
33+
return [index, num_to_index_map[diff]]
34+
35+
return [0, 0]
36+
37+
38+
solution = Solution()
39+
print(solution.twoSum([3, 2, 4], 6))

0 commit comments

Comments
 (0)