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

[kayden] Week 06 Solutions #477

Merged
merged 7 commits into from
Sep 21, 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
17 changes: 17 additions & 0 deletions container-with-most-water/kayden.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# 시간복잡도: O(N)
# 공간복잡도: O(N)
kjb512 marked this conversation as resolved.
Show resolved Hide resolved
class Solution:
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
answer = 0

while l < r:

if height[l] < height[r]:
answer = max(answer, (r - l) * height[l])
l += 1
else:
answer = max(answer, (r - l) * height[r])
r -= 1

return answer
38 changes: 38 additions & 0 deletions design-add-and-search-words-data-structure/kayden.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Node:
def __init__(self, ending=False):
self.ending = ending
self.children = {}


class WordDictionary:

def __init__(self):
self.head = Node(True)

# 시간복잡도: O(W)
def addWord(self, word: str) -> None:
node = self.head

for ch in word:
if ch not in node.children:
node.children.setdefault(ch, Node())
node = node.children[ch]

node.ending = True

# 시간복잡도: O(W*N) W: word 길이 N: 자식 노드의 개수
def search(self, word: str) -> bool:
def dfs(idx, node):
if idx == len(word):
return node.ending

if word[idx] == '.':
for n in node.children.values():
if dfs(idx + 1, n):
return True
elif word[idx] in node.children:
return dfs(idx + 1, node.children[word[idx]])
else:
return False

return dfs(0, self.head)
16 changes: 16 additions & 0 deletions longest-increasing-subsequence/kayden.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 시간복잡도: O(NlogN)
# 공간복잡도: O(N)
from bisect import bisect_left

class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
path = []

for num in nums:
idx = bisect_left(path, num)
Copy link
Contributor

Choose a reason for hiding this comment

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

bisect_left로 정답배열에 들어갈 위치를 지정할 수 있군요..!
리스트에서 num값이 들어갈 위치를 찾는 방법을 적용하는 아이디어는 참신한 아이디어 같아요 👍

if len(path) > idx:
path[idx] = num
else:
path.append(num)

return len(path)
34 changes: 34 additions & 0 deletions spiral-matrix/kayden.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# 시간복잡도: O(N*M)
# 공간복잡도: O(N*M)
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
n = len(matrix[0])
m = len(matrix)
visited = [[False] * n for _ in range(m)]
visited[0][0] = True
answer = []


def dfs(x, y, direction):
answer.append(matrix[x][y])
nx = x + dx[direction]
ny = y + dy[direction]


if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny]:
visited[nx][ny] = True
return dfs(nx, ny, direction)

direction = (direction+1) % 4
nx = x + dx[direction]
ny = y + dy[direction]

if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny]:
visited[nx][ny] = True
return dfs(nx, ny, direction)
else:
return answer
Comment on lines +14 to +32
Copy link
Contributor

Choose a reason for hiding this comment

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

혹시 재귀함수를 사용하신 이유가 있을까요? :)

저는 반복문으로 구현하는 것이 공간 사용 측면에서는 더 효율적일 것 같다는 생각을 했습니다

왜냐하면 위처럼 재귀함수를 사용할 경우 마지막 좌표에 도달할 때까지 재귀함수의 호출 스택만큼의 추가적인 공간을 사용하게 될 것 같거든요

Copy link
Contributor Author

Choose a reason for hiding this comment

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

그래프 탐색이라서 DFS, BFS 라고 생각하고 문제가 한쪽 방향으로 탐색하길래 DFS를 사용하는게 직관적으로 편하다고 생각을 했는데 다시 보니 틀에 박힌 생각이였네요. 단순 반복문을 사용해서 하는게 더 효율적이네요!

좋은 답변 감사합니다! 그래프 탐색은 DFS, BFS라고 틀에박힌 생각을 했네요.


return dfs(0, 0, 0)
19 changes: 19 additions & 0 deletions valid-parentheses/kayden.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# 시간복잡도: O(N)
# 공간복잡도: O(1)
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0:
return False
Comment on lines +5 to +6
Copy link
Contributor

Choose a reason for hiding this comment

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

이 생각 못했네요!


stack = []
matching_brackets = {'(': ')', '{': '}', '[': ']'}

for char in s:
if char in matching_brackets:
stack.append(char)
elif stack and matching_brackets[stack[-1]] == char:
stack.pop()
else:
return False

return not stack