Skip to content

Commit 93c320b

Browse files
committed
two sum solution(py, js)
1 parent 1c8bafb commit 93c320b

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

two-sum/hi-rachel.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
처음 풀이
3+
O(N^2) time, O(N) space
4+
"""
5+
6+
# class Solution:
7+
# def twoSum(self, nums: List[int], target: int) -> List[int]:
8+
# result = []
9+
# for i in range(len(nums)):
10+
# rest = target - nums[i]
11+
# rest_nums = nums[i+1:]
12+
# if rest in rest_nums:
13+
# result.extend([i, rest_nums.index(rest)+i+1])
14+
# break
15+
# return result
16+
17+
18+
"""
19+
개선 코드
20+
O(N) time, O(N) space
21+
"""
22+
23+
class Solution:
24+
def twoSum(self, nums: List[int], target: int) -> List[int]:
25+
indices = {}
26+
27+
for i, v in enumerate(nums):
28+
diff = target - v
29+
if diff in indices:
30+
j = indices[diff]
31+
return [i, j]
32+
indices[v] = i
33+
34+
# JS 풀이
35+
# /**
36+
# * @param {number[]} nums
37+
# * @param {number} target
38+
# * @return {number[]}
39+
# */
40+
# var twoSum = function(nums, target) {
41+
# let indices = new Map();
42+
43+
# for (let i = 0; i < nums.length; i++) {
44+
# diff = target - nums[i];
45+
# if (indices.has(diff)) {
46+
# return [i, indices.get(diff)];
47+
# }
48+
# indices.set(nums[i], i);
49+
# }
50+
# };

0 commit comments

Comments
 (0)