diff --git a/coin-change/sungjinwi.py b/coin-change/sungjinwi.py new file mode 100644 index 000000000..e69de29bb diff --git a/merge-two-sorted-lists/sungjinwi.py b/merge-two-sorted-lists/sungjinwi.py new file mode 100644 index 000000000..236bea895 --- /dev/null +++ b/merge-two-sorted-lists/sungjinwi.py @@ -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 = list1 + list1 = list1.next + else : + node.next = list2 + list2 = list2.next + node = node.next + node.next = list1 or list2 + return dummy.next diff --git a/missing-number/sungjinwi.py b/missing-number/sungjinwi.py new file mode 100644 index 000000000..dd8ebcce8 --- /dev/null +++ b/missing-number/sungjinwi.py @@ -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 diff --git a/word-search/sungjinwi.py b/word-search/sungjinwi.py new file mode 100644 index 000000000..5acc94b8b --- /dev/null +++ b/word-search/sungjinwi.py @@ -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)) + for (r, c) in [(1, 0), (-1, 0), (0, 1), (0, -1)] : + if(dfs(m + r, n + c, idx + 1)) : + return True + 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