Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
Empty file added coin-change/sungjinwi.py
Empty file.
33 changes: 33 additions & 0 deletions merge-two-sorted-lists/sungjinwi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""
기억할 키워드
dummy.next 리턴해서 건너뜀
list1 list2 둘 중 하나가 None이 되면 while문 끝내고 나머지 next로 이어줌

list1의 길이 M, list2의 길이N

TC : O(M + N)

SC : O(1)

추가적인 풀이 : 알고달레에서 재귀방법 확인
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
node = dummy

while list1 and list2 :
if list1.val < list2.val :
node.next = ListNode(list1.val)
Copy link
Contributor

Choose a reason for hiding this comment

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

ListNode의 인스턴스를 새로 생성하기보다, 패러미터로 주어진 값들을 참조하는 방식의 풀이는 어떨까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

아 새로 안 만들고 바로 그냥 list1, list2를 할당해주면 되겠네요
어차피 next는 계속 업데이트되니까요! 감사합니다

list1 = list1.next
else :
node.next = ListNode(list2.val)
list2 = list2.next
node = node.next
node.next = list1 or list2
Copy link
Contributor

Choose a reason for hiding this comment

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

안녕하세요 @sungjinwi

덕분에 if 문 없이 list1 or list2 으로 처리되는걸 알게 되었습니다.
감사합니다. 😊

return dummy.next
16 changes: 16 additions & 0 deletions missing-number/sungjinwi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
풀이 : 비지 않을경우 합 nSum을 구하고 list를 돌면서 빼고 남은 것이 답


TC : O(N)
sum구할 떄 O(N) + for문 O(N) = O(2N)\

SC : O(1)
"""

class Solution:
def missingNumber(self, nums: List[int]) -> int:
nSum = sum(range(0,len(nums) + 1))
for num in nums :
nSum -=num
return nSum
47 changes: 47 additions & 0 deletions word-search/sungjinwi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
풀이 :
상하좌우 이동한 좌표가 board범위 벗어나면 False
board[m][n]이 word[idx]와 불일치하면 False
이미 방문했을경우 False
단어가 완성되면 True
상하좌우 한칸 이동한칸에 대해 재귀적 호출
상하좌우 중 True 있으면 True 없으면 False

TC : O(M * N * 4 ^ W)
board의 크기에 비례 -> M * N
단어의 길이 만큼 상하좌우 재귀 호출 -> 4 ^ W

SC : O(M * N + W)
set의 메모리는 board 크기에 비례 -> M * N
함수 호출 스택은 단어 길이에 비례 -> W
"""

class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
visit = set()

def dfs(m: int, n: int, idx: int) -> bool:
if not (0 <= m < row and 0 <= n < col):
return False
if not board[m][n] == word[idx]:
return False
if (m, n) in visit:
return False
if idx == len(word) - 1:
return True

visit.add((m, n))
if any (dfs(m + r, n + c, idx + 1) \
for (r, c) in [(1, 0), (-1, 0), (0, 1), (0, -1)]):
return True
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

Choose a reason for hiding this comment

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

for문을 조회하면서 dfs를 실행시키고, 그 결과들 중 하나라도 True면, True를 반환하는 로직입니다
간편하기는 하지만 가독성을 향상시키는 방법으로 코드를 개선해보시면 어떨까 싶어요, 그리고 any는 iterable이 생성된 후 실행되기 때문에 early return으로 성능을 향상시킬 수도 있을 것 같아요.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

안녕하세요 any() 함수를 활용해보고 싶어서 저렇게 작성했는데요
any함수는 iterable 중에 0(False)이 아닌 것이 존재하면 True를 리턴합니다

dfs(m + 1, n, idx + 1)
dfs(m - 1, n, idx + 1)
dfs(m, n + 1, idx + 1)
dfs(m, n - 1, idx + 1)
# 상하좌우 재귀호출 된 결과 중 True가 있다면 True를 리턴하도록 했습니다

다시 보니 이렇게 풀이하는게 연산이 조금이라도 덜 일어날 것 같네요

for (r, c) in [(1, 0), (-1, 0), (0, 1), (0, -1)]) :
       if(dfs(m + r, n + c, idx + 1)) :
              return True

좋은 질문 감사합니다 또 궁금한거 있으시면 질문주세요!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@EgonD3V 매주 좋은 리뷰 감사합니다!

visit.remove((m, n))
return False

row = len(board)
col = len(board[0])

for m in range(row):
for n in range(col):
if dfs(m, n, 0):
return True
return False
Loading