Skip to content
Open
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
28 changes: 28 additions & 0 deletions climbing-stairs/riveroverflows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from typing import *


class Solution:
"""
TC: O(n)
- memo = [-1] * (n+1): O(n)
- for num in range(3, n+1): O(n)
최종: O(n)

SC: O(n)
- memo: O(n)

풀이:
n번째 계단까지 올라가는 방법의 수는 (n-1번째 방법의 수) + (n-2번째 방법의 수).
피보나치수열과 동일한 점화식. memoization으로 중복 계산 방지.
"""
def climbStairs(self, n: int) -> int:
if n < 2:
return 1
memo = [-1] * (n + 1)
memo[1] = 1
memo[2] = 2

for num in range(3, n + 1):
memo[num] = memo[num - 1] + memo[num - 2]

return memo[n]
49 changes: 49 additions & 0 deletions product-of-array-except-self/riveroverflows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from typing import *


class Solution:
"""
TC: O(n)
- left 배열 생성: O(n)
- right 배열 생성: O(n)
- answer 배열 생성: O(n)
최종: O(n)

SC: O(n)
- left, right, answer 배열 각각 O(n)
최종: O(n)

풀이:
나누기 없이 풀기 위해 각 인덱스 기준 왼쪽 원소들의 곱(left), 오른쪽 원소들의 곱(right) 배열을 별도로 만들고
answer[i] = left[i-1] * right[i+1] 로 계산.
i=0이면 왼쪽 곱 없으므로 right[i+1]만, i=마지막이면 left[i-1]만 사용.
"""
def productExceptSelf(self, nums: List[int]) -> List[int]:
nums_len = len(nums)
last_index = nums_len - 1

left = [0] * nums_len
for i, num in enumerate(nums):
if i == 0:
left[i] = num
continue
left[i] = left[i - 1] * num

right = [0] * nums_len
for i in range(last_index, -1, -1):
if i == last_index:
right[i] = nums[i]
continue
right[i] = right[i + 1] * nums[i]

answer = [0] * nums_len
for i in range(nums_len):
if i == 0:
answer[i] = right[i + 1]
continue
if i == last_index:
answer[i] = left[i - 1]
continue
answer[i] = left[i - 1] * right[i + 1]

return answer
34 changes: 34 additions & 0 deletions valid-anagram/riveroverflows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import *


class Solution:
"""
풀이:
s와 t 길이가 다르면 anagram 아니므로 False로 early return
set으로 s의 중복 문자 제거
set을 순회하면서 각 문자가 s와 t에서 등장하는 횟수가 동일한지 확인
다르면 False, 끝까지 통과하면 True

TC: O(n+m)
- if len(s) != len(t): O(1)
- ss = set(s): O(n)
- for c in ss: 최대 26회 반복 → O(1)
- s.count(c): O(n)
- t.count(c): O(m)
- 최종: O(n+m)

SC: O(n)
- ss = set(s): 최악의 경우 O(n)
- 그 외 상수: O(1)
- 최종: O(n)
"""
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False

ss = set(s)
for c in ss:
if s.count(c) != t.count(c):
return False

return True
Loading