Skip to content

Commit 3580481

Browse files
committed
leetcode - 1
1 parent 79e6273 commit 3580481

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

python/array/leetcode_1.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# LeetCode
2+
# 1. Two Sum
3+
# https://leetcode.com/problems/two-sum/description/
4+
5+
def twoSum(nums, target: int):
6+
# 1. 무식하게 전부 해 보는 방법 O(n^2)
7+
8+
for i in range(0, len(nums)):
9+
for j in range(i+1, len(nums)):
10+
if nums[i]+nums[j] == target:
11+
return [i, j]
12+
13+
# 2. 첫 번째 수를 빼면 두 번째 값이 바로 나오기 때문에 dic로 조회 O(n)
14+
dic = {}
15+
16+
for index, num in enumerate(nums):
17+
dic[num] = index
18+
19+
for i, num in enumerate(nums):
20+
if (target - num) in dic and i != dic[target-num]:
21+
return [i, dic[target-num]]
22+
23+
# 투 포인터 풀이 -> 정렬된 값으로 오지 않기 때문에 사용 불가능
24+
25+
twoSum([2,7,11,15], 9)

0 commit comments

Comments
 (0)