Skip to content

Commit

Permalink
modifications
Browse files Browse the repository at this point in the history
  • Loading branch information
haklee committed Oct 4, 2024
1 parent 7487dc0 commit e55cc8c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
24 changes: 18 additions & 6 deletions longest-common-subsequence/haklee.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,13 @@
SC:
- ์ฒซ ๋ฒˆ์งธ ๋ฌธ์ž์—ด์˜ ์•ž i๊ธ€์ž๋กœ ๋งŒ๋“  ๋ฌธ์ž์—ด๊ณผ ๋‘ ๋ฒˆ์งธ ๋ฌธ์ž์—ด์˜ ์•ž j๊ธ€์ž๋กœ ๋งŒ๋“  ๋ฌธ์ž์—ด์˜ lcs์˜
๊ธธ์ด๋ฅผ ๊ด€๋ฆฌ.
- O(m * n)
- ๊ทธ๋Ÿฐ๋ฐ ์•„์ด๋””์–ด์— ์ œ์‹œ๋œ ์ ํ™”์‹์„ ๋ณด๋ฉด i, j๊ฐ’์— ๋Œ€ํ•œ ์ „์ฒด ๋ฐฐ์—ด์„ ์ €์žฅํ•  ํ•„์š” ์—†์ด i=k์ผ๋•Œ
๊ฐ’์„ ๊ตฌํ•˜๋ ค ํ•œ๋‹ค๋ฉด i=k-1์ผ๋•Œ ๊ตฌํ•œ lcs๊ฐ’๋งŒ ์•Œ๊ณ  ์žˆ์œผ๋ฉด ์ถฉ๋ถ„ํ•˜๋‹ค.
- ์ฆ‰, ๋ฐฐ์—ด์€ ํ˜„์žฌ ๊ตฌํ•˜๊ณ ์ž ํ•˜๋Š” i๊ฐ’์— ๋Œ€ํ•œ j๊ฐœ์˜ ์•„์ดํ…œ๊ณผ ์ง์ „์— ๊ตฌํ•œ j๊ฐœ์˜ ์•„์ดํ…œ๋งŒ ์ €์žฅํ•˜๋ฉด
์ถฉ๋ถ„ํ•˜๋‹ค. ์ฆ‰, text2์˜ ๊ธธ์ด์ธ O(n)์ด๋ผ๊ณ  ๋ณผ ์ˆ˜ ์žˆ๋‹ค.
- ๊ทธ๋Ÿฐ๋ฐ ๋งŒ์•ฝ text2์˜ ๊ธธ์ด๊ฐ€ text1๋ณด๋‹ค ๊ธธ๋ฉด ์ด ๋‘˜์„ ๋ฐ”๊ฟ”์น˜๊ธฐํ•ด์„œ ์œ„์˜ ๊ณต๊ฐ„๋ณต์žก๋„๋ฅผ O(m)์ด๋ผ๊ณ 
๋ด๋„ ์•„์ด๋””์–ด ์ž์ฒด๋Š” ๋˜‘๊ฐ™์ด ์ž‘๋™ํ•˜์ง€ ์•Š๋Š”๊ฐ€?
- ์ฆ‰, O(min(m, n))
TC:
- dp ๋ฐฐ์—ด์„ ์ฑ„์šฐ๋Š” ๋ฐ์— ๋งˆ์ง€๋ง‰ ๋ฌธ์ž๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ ๋‹จ์ˆœ ๋ง์…ˆ, ๋‹ค๋ฅผ ๊ฒฝ์šฐ ๋‘ ๊ฐ’ ๋น„๊ต. ๋‘˜ ๋‹ค O(1).
Expand All @@ -39,14 +45,20 @@

class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
dp = [[0 for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)]
if len(text2) > len(text1):
# ์ด ์ตœ์ ํ™”๊นŒ์ง€ ํ•ด์ฃผ๋ฉด ์‚ฌ์šฉํ•˜๋Š” ๋ฉ”๋ชจ๋ฆฌ ํฌ๊ธฐ๊ฐ€ ๋งŽ์ด ์ค„์–ด๋“ค ์ˆ˜ ์žˆ๋‹ค.
text1, text2 = text2, text1

dp = [[0 for _ in range(len(text2) + 1)] for _ in range(2)]

for i in range(1, len(text1) + 1):
i_prev = (i + 1) % 2
i_cur = i % 2
for j in range(1, len(text2) + 1):
dp[i][j] = (
dp[i - 1][j - 1] + 1
dp[i_cur][j] = (
dp[i_prev][j - 1] + 1
if text1[i - 1] == text2[j - 1]
else max(dp[i - 1][j], dp[i][j - 1])
else max(dp[i_prev][j], dp[i_cur][j - 1])
)

return dp[-1][-1]
return dp[i_cur][-1]
8 changes: 4 additions & 4 deletions sum-of-two-integers/haklee.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def getSum(self, a: int, b: int) -> int:
b์˜ ๋ฒ”์œ„๊ฐ€ ์ œํ•œ๋˜์–ด ์žˆ์–ด์„œ ์ ‘๊ทผ ๋ถˆ๊ฐ€๋Šฅํ•œ, ์ฆ‰, ํ•„์š” ์—†๋Š” ์ˆซ์ž๋“ค์ด๋ผ๊ณ  ๋ณด๋ฉด ๋œ๋‹ค.
SC:
- O(n^2). ์ •ํ™•ํžˆ๋Š”, (2*n+1)^2 ๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ๋ฐฐ์—ด์— ์ €์žฅํ•œ๋‹ค.
- ์ฝ”๋“œ ์ฐธ์กฐ. O(n).
TC:
- ์ธ๋ฑ์Šค๋ฅผ ํ†ตํ•ด ๋ฐ”๋กœ ์ ‘๊ทผ. O(1).
Expand All @@ -127,7 +127,7 @@ class Solution:
def getSum(self, a: int, b: int) -> int:
x = list(range(0, 2001))
x.extend(list(range(-2000, 0)))
v = x * 2
s = list(range(0, 4001))
e = list(range(4001, 8002))
v = x * 2 # SC: O(n)
s = list(range(0, 4001)) # SC: O(n)
e = list(range(4001, 8002)) # SC: O(n)
return v[s[a] : e[a]][b]

0 comments on commit e55cc8c

Please sign in to comment.