Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[HaJunYoo] Week 2 #376

Merged
merged 8 commits into from
Aug 28, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Definition for a binary tree node.
from typing import List


class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution:
# time complexity: O(n)
# space complexity: O(n)
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if not preorder or not inorder:
return None

val = preorder.pop(0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pop(0)시간복잡도는 O(N)입니다.
해당 method의 시간복잡도 때문에 알고리즘 전체 시간 복잡도도 증가할 것으로 추측되는데, 다른 방안을 고려해보는 것도 좋을 것 같아요

mid = inorder.index(val)
left = self.buildTree(preorder, inorder[:mid])
right = self.buildTree(preorder, inorder[mid + 1:])

return TreeNode(val, left, right)
34 changes: 34 additions & 0 deletions counting-bits/hajunyoo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution1:
# time complexity: O(n)
# space complexity: O(1)
def countBits(self, n: int) -> List[int]:
list = [i for i in range(n + 1)]
result = [bin(num).count('1') for num in list]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

전체 시간 복잡도에 str.count() method의 시간복잡도 또한 고려해보는게 좋을 것 같습니다

return result

class Solution2:
# time complexity: O(n * logn)
# space complexity: O(1)
def countBits(self, n: int) -> List[int]:

def count(num):
cnt = 0
while num:
cnt += num % 2
num //= 2
return cnt

res = [count(i) for i in range(n+1)]
return res

class Solution3:
# time complexity: O(n)
# space complexity: O(1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q
공간 복잡도는 답안 배열을 제외하고 O(1)로 계산하신걸까요??

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

앗 그렇네요!
O(n)이 맞습니다
감사드려요 ㅎㅎ

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O(n)이 맞습니다 ㅎㅎ 제가 고려를 못했습니다

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

분석하는 사람에 따라 답안으로 제출하는 Object의 공간 복잡도는 고려하지 않기도 합니다.
저는 풀이에 필요한 추가적인 공간 복잡도만 계산하는 편이에요.

def countBits(self, n: int) -> List[int]:
res = [0] * (n + 1)
msb = 1
for i in range(1, n + 1):
if i == msb * 2:
msb *= 2
res[i] = res[i - msb] + 1
return res
Comment on lines +27 to +34
Copy link
Contributor

@wogha95 wogha95 Aug 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 이렇게도 index를 계산해서 풀 수 있겠군요! 👍

그런데 혹시 msb 네이밍 사용이 궁금합니다!
현 로직과 msb와 다른 풀이 방향이 아닐까 싶어 의문이 들었습니다🤔
제가 부족하게 이해하였다면 추가 설명을 듣고 싶습니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

원래는 mhb(most highest bit)로 했다가 최상위 비트라는 네이밍으로 검색해서 수정했습니다 ㅎㅎ

21 changes: 21 additions & 0 deletions decode-ways/hajunyoo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution:
# time complexity: O(n)
# space complexity: O(n)
def numDecodings(self, s: str) -> int:
if not s or s.startswith('0'):
return 0

n = len(s)
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 1 if s[0] != '0' else 0

for i in range(2, n + 1):
if s[i - 1] != '0':
dp[i] += dp[i - 1]

two_digit = int(s[i - 2:i])
if 10 <= two_digit <= 26:
dp[i] += dp[i - 2]

return dp[n]
31 changes: 31 additions & 0 deletions encode-and-decode-strings/hajunyoo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution1:
# time complexity: O(n)
# space complexity: O(1)
def encode(self, strs):
return ":;".join(strs)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image ':', ';' 둘 모두 ASCII 256에 포함되어 있는 문자라서 아래 테스트 케이스에 대해서는 오류가 발생할 것 같아요
Encode
input: ["asdf:;:;:;", "asdfasdf"]
output: "asdf:;:;:;:;asdfasdf"

Decode
input: "asdf:;:;:;:;asdfasdf"
output: ["asdf", "", "", "", "asdfasdf"]


# time complexity: O(n)
# space complexity: O(1)
def decode(self, str):
return str.split(":;")

class Solution2:
# time complexity: O(n)
# space complexity: O(1)
def encode(self, strs):
txt = ""
for s in strs:
txt += str(len(s)) + ":" + s
return txt

# time complexity: O(n)
# space complexity: O(1)
def decode(self, str):
res = []
i = 0
while i < len(str):
colon = str.find(":", i)
length = int(str[i:colon])
res.append(str[colon + 1:colon + 1 + length])
i = colon + 1 + length
return res
27 changes: 27 additions & 0 deletions valid-anagram/hajunyoo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from collections import defaultdict


class Solution:
# Time complexity: O(n)
# Space complexity: O(n)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alphabet의 개수는 26개로 고정되어 있기 때문에 hashmap의 key도 26을 넘을 수 없다는 걸 알수 있습니다
따라서 공간 복잡도는 사실상 O(1)이라고 봐도 무방할 것 같아요

def isAnagram(self, s: str, t: str) -> bool:
char_map = defaultdict(int)
for s1 in s:
char_map[s1] += 1

contrast_map = defaultdict(int)
for t1 in t:
contrast_map[t1] += 1

for key, val in char_map.items():
contrast_val = contrast_map[key]
if contrast_val != val:
return False

for key, val in contrast_map.items():
char_val = char_map[key]
if char_val != val:
return False
Comment on lines +8 to +24
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

char_map, contrast_map <- 이렇게 hashmap을 두 개 선언하여 st의 알파벳 개수를 세는 것도 괜찮지만
아래처럼 char_map 하나만 사용하면 사용하는 공간을 반으로 줄이고, 결과를 확인하는 반복문도 반으로 줄일 수 있을 것 같아요

char_map = defaultdict(int)

for s1 in s:
    char_map[s1] += 1
for t1 in t:
    char_map[t1] -= 1

for key in char_map:
    if char_map[key]:
        return False
return True


return True