Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions 3sum/devyulbae.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""
Blind 75 - LeetCode Problem 15. 3Sum
https://leetcode.com/problems/3sum/
시간복잡도 O(n^2)
"""
from typing import List

class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
answer = []
n = len(nums)

for i in range(n):
if i > 0 and nums[i] == nums[i - 1]:
continue # 중복 원소 스킵

left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]

if total == 0:
answer.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1

# 중복값 건너뛰기
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1

elif total < 0:
left += 1 # 합이 작으니 left를 키워야 함

else:
right -= 1 # 합이 크니 right를 줄여야 함

return answer

25 changes: 25 additions & 0 deletions climbing-stairs/devyulbae.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
Blind 75 - LeetCode Problem 70. Climbing Stairs
https://leetcode.com/problems/climbing-stairs/

계단이 n개, 한 번에 1칸 또는 2칸씩 오를 수 있다.
combinations를 썼더니 시간초과 발생 (O(2^n))

DP를 이용해 시간복잡도 O(n) 공간복잡도 O(1)로 풀기
f(n) = f(n-1) + f(n-2)
"""
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n

one_before = 2 # n=2
two_before = 1 # n=1

for _ in range(3, n+1):
current = one_before + two_before # f(1) = f(n-1) + f(n-2)
two_before = one_before # f 밀기
one_before = current # f 밀기

return current

38 changes: 38 additions & 0 deletions product-of-array-except-self/devyulbae.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
Blind75 - 4. Product of Array Except Self
https://leetcode.com/problems/product-of-array-except-self/
조건 :
- 분할 없이 O(n) 시간 복잡도 이하로 풀어라
- nums의 모든 원소의 곱은 32비트 정수 범위 내에 들어온다
- 나눗셈 금지

0이 몇개인가?
- 2개 이상 : 모두 0인 배열
- 1개 : 0 본인 제외는 0인 배열
- 0개 : 좌 우 각각의 메모이제이션을 해주면 O(2n)으로 배열 생성, O(n)으로 정답 배열 생성하므로 O(n)
"""
from typing import List

class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
zero_count = nums.count(0)
if zero_count > 1:
return [0] * len(nums)
elif zero_count == 1:
all_product = 1
for num in nums:
all_product *= num if num != 0 else 1
return [0 if num!= 0 else all_product for num in nums]

else:
left_product = [nums[0]]
right_product = [nums[-1]]
for i in range(1,len(nums)):
left_product.append(left_product[i-1]*nums[i])
right_product.append(right_product[i-1]*nums[-1-i])

answer = []
for i in range(len(nums)):
answer.append((left_product[i-1] if i>0 else 1)* (right_product[-2-i] if i < len(nums)-1 else 1))
return answer

15 changes: 15 additions & 0 deletions valid-anagram/devyulbae.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""
Blind 75 - LeetCode Problem 242: Valid Anagram
https://leetcode.com/problems/valid-anagram/

t가 s의 애너그램인지 확인하기
"""
from collections import Counter

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False

return Counter(s) == Counter(t)

35 changes: 35 additions & 0 deletions validate-binary-search-tree/devyulbae.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
Blind 75 - LeetCode Problem 98: Validate Binary Search Tree
https://leetcode.com/problems/validate-binary-search-tree/

중위 순회 - 왼쪽 서브트리 -> 루트 -> 오른쪽 서브트리
중위 순회한 값이 오름차순인지 확인하면 된다.
"""
from typing import Optional, List

# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution: # root = [2,1,3] answer = True
def traverse(self, node: Optional[TreeNode], inorder: List[int]) -> None:
if not node:
return
self.traverse(node.left, inorder)
inorder.append(node.val)
self.traverse(node.right, inorder)


def isValidBST(self, root: Optional[TreeNode]) -> bool:
inorder = []
self.traverse(root, inorder)

for i in range(1, len(inorder)):
if inorder[i] <= inorder[i-1]:
return False

return True