From 5fffdb09e9783fda0cfa00341d1e8ea7d725402e Mon Sep 17 00:00:00 2001 From: iamminji Date: Fri, 26 Aug 2022 19:31:31 +0900 Subject: [PATCH 01/24] Add leetcode common collections --- common/__init__.py | 0 common/leetcodeds.py | 11 +++++++++++ common/pp.py | 37 ++++++++++++++++++++++++++++--------- 3 files changed, 39 insertions(+), 9 deletions(-) create mode 100644 common/__init__.py create mode 100644 common/leetcodeds.py diff --git a/common/__init__.py b/common/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/common/leetcodeds.py b/common/leetcodeds.py new file mode 100644 index 0000000..64116aa --- /dev/null +++ b/common/leetcodeds.py @@ -0,0 +1,11 @@ +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None diff --git a/common/pp.py b/common/pp.py index 39651e7..dac3c77 100644 --- a/common/pp.py +++ b/common/pp.py @@ -1,11 +1,5 @@ from collections import deque - - -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None +from common.leetcodeds import * class FullBinaryTreeNodePrettyPrinter: @@ -18,7 +12,7 @@ class FullBinaryTreeNodePrettyPrinter: """ @classmethod - def pp(cls, node): + def pp(cls, node: TreeNode): queue = deque() queue.append(node) ans = [] @@ -31,4 +25,29 @@ def pp(cls, node): queue.append(n.right) else: ans.append(None) - return ans + print(ans) + + +def list_to_ListNode(l: list) -> ListNode: + dummy = start = ListNode() + for val in l: + start.next = ListNode(val) + start = start.next + + return dummy.next + + +if __name__ == '__main__': + sample = TreeNode(1) + sample.left = TreeNode(2) + sample.right = TreeNode(3) + sample.left.left = TreeNode(5) + sample.right.right = TreeNode(7) + + # [1, 2, 3, 5, None, None, 7] + FullBinaryTreeNodePrettyPrinter.pp(sample) + + sample1 = list_to_ListNode([1, 2, 3, 4, 5]) + while sample1 is not None: + print(sample1.val) + sample1 = sample1.next From b9ee0270fab4f76f77ca147b98fcc709b7aa9a06 Mon Sep 17 00:00:00 2001 From: iamminji Date: Fri, 26 Aug 2022 19:32:13 +0900 Subject: [PATCH 02/24] =?UTF-8?q?[20220826]=20leetcode=20study-plan=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- study-plan/leetcode-75/day2-is-subsequence.py | 21 ++++++ .../leetcode-75/day2-isomorphic-strings.py | 30 ++++++++ .../day3-merge-two-sorted-lists.py | 70 +++++++++++++++++++ .../leetcode-75/day3-reverse-linked-list.py | 48 +++++++++++++ 4 files changed, 169 insertions(+) create mode 100644 study-plan/leetcode-75/day2-is-subsequence.py create mode 100644 study-plan/leetcode-75/day2-isomorphic-strings.py create mode 100644 study-plan/leetcode-75/day3-merge-two-sorted-lists.py create mode 100644 study-plan/leetcode-75/day3-reverse-linked-list.py diff --git a/study-plan/leetcode-75/day2-is-subsequence.py b/study-plan/leetcode-75/day2-is-subsequence.py new file mode 100644 index 0000000..f1369c6 --- /dev/null +++ b/study-plan/leetcode-75/day2-is-subsequence.py @@ -0,0 +1,21 @@ +# https://leetcode.com/problems/is-subsequence/ +# 392. Is Subsequence + +class Solution: + def isSubsequence(self, s: str, t: str) -> bool: + i, j = 0, 0 + while i < len(s) and j < len(t): + if s[i] == t[j]: + i += 1 + j += 1 + else: + j += 1 + + return i == len(s) + + +if __name__ == '__main__': + sol = Solution() + print(sol.isSubsequence("abc", "ahbgdc")) + print(sol.isSubsequence("axc", "ahbgdc")) + print(sol.isSubsequence("b", "abc")) diff --git a/study-plan/leetcode-75/day2-isomorphic-strings.py b/study-plan/leetcode-75/day2-isomorphic-strings.py new file mode 100644 index 0000000..3b39796 --- /dev/null +++ b/study-plan/leetcode-75/day2-isomorphic-strings.py @@ -0,0 +1,30 @@ +# https://leetcode.com/problems/isomorphic-strings/ +# 205. Isomorphic Strings + +from collections import defaultdict + + +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + sdic = defaultdict() + tdic = defaultdict() + if len(s) != len(t): + return False + + for a, b in zip(s, t): + sdic[a] = b + tdic[b] = a + + for a, b in zip(s, t): + if sdic[a] != b or tdic[b] != a: + return False + + return True + + +if __name__ == '__main__': + sol = Solution() + print(sol.isIsomorphic("egg", "add")) + print(sol.isIsomorphic("foo", "bar")) + print(sol.isIsomorphic("paper", "title")) + print(sol.isIsomorphic("badc", "baba")) diff --git a/study-plan/leetcode-75/day3-merge-two-sorted-lists.py b/study-plan/leetcode-75/day3-merge-two-sorted-lists.py new file mode 100644 index 0000000..3edc909 --- /dev/null +++ b/study-plan/leetcode-75/day3-merge-two-sorted-lists.py @@ -0,0 +1,70 @@ +# https://leetcode.com/problems/merge-two-sorted-lists/ +# 21. Merge Two Sorted Lists + +from typing import Optional + + +# 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]: + # ListNode 생성 하여 풀이 (AC) + + if list1 is not None and list2 is None: + return list1 + + if list1 is None and list2 is not None: + return list2 + + if list1 is None and list2 is None: + return None + + start = dummy = ListNode() + + while list1 is not None and list2 is not None: + if list1.val < list2.val: + start.next = list1 + list1 = list1.next + elif list1.val == list2.val: + start.next = list1 + list1 = list1.next + else: + start.next = list2 + list2 = list2.next + start = start.next + + if list1 is not None and list2 is None: + start.next = list1 + + if list2 is not None and list1 is None: + start.next = list2 + + return dummy.next + + def mergeTwoLists_2(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: + # ListNode 생성 없이 풀이 (Discuss 참고) + # 작은 값을 가진 리스트 노드를 이동 시켜서 연결 시키면 됨 + + # list1이 None 이면 list2 가 list1의 가장 큰 값 보다 크다는 의미이므로 + # list2 를 리턴시킨다. + if list1 is None: + return list2 + + if list2 is None: + return list1 + + if list1.val < list2.val: + # list1을 이동시킴 + # 그리고 결과로 나온 값 (최소 l1 보다 큰 값) 을 l1 에 이어 붙인다. + list1.next = self.mergeTwoLists_2(list1.next, list2) + return list1 + else: + # list2 이동 + # 같으면 사실 list1 이든 list2 든 누가 이동해도 상관 없음 (어느쪽에 붙여든 상관 없음) + list2.next = self.mergeTwoLists_2(list1, list2.next) + return list2 diff --git a/study-plan/leetcode-75/day3-reverse-linked-list.py b/study-plan/leetcode-75/day3-reverse-linked-list.py new file mode 100644 index 0000000..908fe30 --- /dev/null +++ b/study-plan/leetcode-75/day3-reverse-linked-list.py @@ -0,0 +1,48 @@ +# https://leetcode.com/problems/reverse-linked-list/ +# 206. Reverse Linked List + +from typing import Optional + + +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + def __str__(self) -> str: + return str(self.val) + + +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + + if head is None: + return None + + start = dummy = ListNode() + + stack = [] + while head is not None: + stack.append(head.val) + head = head.next + + while stack: + start.next = ListNode(stack.pop()) + start = start.next + + return dummy.next + + def reverseList_2(self, head: Optional[ListNode]) -> Optional[ListNode]: + # TODO stack 사용 없이 풀어보기 + pass + + +if __name__ == '__main__': + sol = Solution() + cur = node = ListNode() + for i in range(1, 6): + node.next = ListNode(i) + node = node.next + + print(sol.reverseList_2(cur.next)) From f7f7a08a929fcdae3eb76ec22edd06eb546d7288 Mon Sep 17 00:00:00 2001 From: iamminji Date: Mon, 29 Aug 2022 21:10:36 +0900 Subject: [PATCH 03/24] =?UTF-8?q?[20220829]=20leetcode=20study-plan=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leetcode-75/day4-linked-list-cycle-ii.py | 45 +++++++++++++++++++ .../day4-middle-of-the-linked-list.py | 27 +++++++++++ 2 files changed, 72 insertions(+) create mode 100644 study-plan/leetcode-75/day4-linked-list-cycle-ii.py create mode 100644 study-plan/leetcode-75/day4-middle-of-the-linked-list.py diff --git a/study-plan/leetcode-75/day4-linked-list-cycle-ii.py b/study-plan/leetcode-75/day4-linked-list-cycle-ii.py new file mode 100644 index 0000000..7e18bad --- /dev/null +++ b/study-plan/leetcode-75/day4-linked-list-cycle-ii.py @@ -0,0 +1,45 @@ +# https://leetcode.com/problems/linked-list-cycle-ii/ +# 142. Linked List Cycle II + +from typing import Optional +from common.leetcodeds import ListNode + + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: + if head is None: + return None + slow, fast = head, head + cycle = False + + while fast is not None and fast.next is not None: + slow = slow.next + fast = fast.next.next + + if slow == fast: + cycle = True + break + + if not cycle: + return None + + while head != slow: + head = head.next + slow = slow.next + return slow + + +if __name__ == '__main__': + node = ListNode(3) + node.next = ListNode(2) + node.next.next = ListNode(0) + node.next.next.next = ListNode(-4) + node.next.next.next.next = node.next + sol = Solution() + print(sol.detectCycle(node)) diff --git a/study-plan/leetcode-75/day4-middle-of-the-linked-list.py b/study-plan/leetcode-75/day4-middle-of-the-linked-list.py new file mode 100644 index 0000000..8ae683c --- /dev/null +++ b/study-plan/leetcode-75/day4-middle-of-the-linked-list.py @@ -0,0 +1,27 @@ +# https://leetcode.com/problems/middle-of-the-linked-list/ +# 876. Middle of the Linked List + +from typing import Optional +from common.leetcodeds import ListNode + + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: + first, second = head, head + + if head.next is None: + return head + + while second is not None and second.next is not None: + first = first.next + second = second.next.next + + return first + From 61b49358a0c7071d02d295fb75a7bb8577723404 Mon Sep 17 00:00:00 2001 From: iamminji Date: Tue, 30 Aug 2022 19:26:01 +0900 Subject: [PATCH 04/24] [20220830] solve the problems --- common/leetcodeds.py | 6 +++ .../leetcode-75/day3-reverse-linked-list.py | 23 ++++++----- .../day5-best-time-to-buy-and-sell-stock.py | 19 +++++++++ .../leetcode-75/day5-longest-palindrome.py | 30 ++++++++++++++ .../day6-binary-tree-level-order-traversal.py | 39 +++++++++++++++++++ .../day6-n-ary-tree-preorder-traversal.py | 30 ++++++++++++++ study-plan/leetcode-75/day7-binary-search.py | 27 +++++++++++++ .../leetcode-75/day7-first-bad-version.py | 24 ++++++++++++ 8 files changed, 186 insertions(+), 12 deletions(-) create mode 100644 study-plan/leetcode-75/day5-best-time-to-buy-and-sell-stock.py create mode 100644 study-plan/leetcode-75/day5-longest-palindrome.py create mode 100644 study-plan/leetcode-75/day6-binary-tree-level-order-traversal.py create mode 100644 study-plan/leetcode-75/day6-n-ary-tree-preorder-traversal.py create mode 100644 study-plan/leetcode-75/day7-binary-search.py create mode 100644 study-plan/leetcode-75/day7-first-bad-version.py diff --git a/common/leetcodeds.py b/common/leetcodeds.py index 64116aa..c9ad746 100644 --- a/common/leetcodeds.py +++ b/common/leetcodeds.py @@ -9,3 +9,9 @@ def __init__(self, x): self.val = x self.left = None self.right = None + + +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children diff --git a/study-plan/leetcode-75/day3-reverse-linked-list.py b/study-plan/leetcode-75/day3-reverse-linked-list.py index 908fe30..c157078 100644 --- a/study-plan/leetcode-75/day3-reverse-linked-list.py +++ b/study-plan/leetcode-75/day3-reverse-linked-list.py @@ -2,16 +2,7 @@ # 206. Reverse Linked List from typing import Optional - - -# Definition for singly-linked list. -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - - def __str__(self) -> str: - return str(self.val) +from common.leetcodeds import ListNode class Solution: @@ -34,8 +25,16 @@ def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: return dummy.next def reverseList_2(self, head: Optional[ListNode]) -> Optional[ListNode]: - # TODO stack 사용 없이 풀어보기 - pass + if head is None: + return None + + prev, cur = None, head + while head is not None: + head = head.next + cur.next = prev + prev = cur + cur = head + return prev if __name__ == '__main__': diff --git a/study-plan/leetcode-75/day5-best-time-to-buy-and-sell-stock.py b/study-plan/leetcode-75/day5-best-time-to-buy-and-sell-stock.py new file mode 100644 index 0000000..e79c12b --- /dev/null +++ b/study-plan/leetcode-75/day5-best-time-to-buy-and-sell-stock.py @@ -0,0 +1,19 @@ +# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ +# 121. Best Time to Buy and Sell Stock +from typing import List + + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + cur = prices[0] + result = 0 + for i in range(1, len(prices)): + result = max(prices[i] - cur, result) + cur = min(prices[i], cur) + + return result + + +if __name__ == '__main__': + sol = Solution() + print(sol.maxProfit([7, 1, 5, 3, 6, 4])) diff --git a/study-plan/leetcode-75/day5-longest-palindrome.py b/study-plan/leetcode-75/day5-longest-palindrome.py new file mode 100644 index 0000000..4be09ec --- /dev/null +++ b/study-plan/leetcode-75/day5-longest-palindrome.py @@ -0,0 +1,30 @@ +# https://leetcode.com/problems/longest-palindrome/ +# 409. Longest Palindrome + +from collections import Counter + + +class Solution: + def longestPalindrome(self, s: str) -> int: + counter = Counter(s) + + result = 0 + for k, v in counter.items(): + if v % 2 == 0: + result += v + counter[k] = 0 + elif v % 2 != 0 and v >= 2: + result += v - 1 + counter[k] -= 1 + + for k, v in counter.items(): + if v > 0: + result += 1 + break + return result + + +if __name__ == '__main__': + sol = Solution() + print(sol.longestPalindrome("abccccdd")) + print(sol.longestPalindrome("a")) diff --git a/study-plan/leetcode-75/day6-binary-tree-level-order-traversal.py b/study-plan/leetcode-75/day6-binary-tree-level-order-traversal.py new file mode 100644 index 0000000..0edcc9b --- /dev/null +++ b/study-plan/leetcode-75/day6-binary-tree-level-order-traversal.py @@ -0,0 +1,39 @@ +# https://leetcode.com/problems/binary-tree-level-order-traversal/ +# 102. Binary Tree Level Order Traversal +from typing import Optional, List +from common.leetcodeds import TreeNode + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + +from collections import deque + + +class Solution: + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + result = [] + if root is None: + return result + + queue = deque() + queue.append((0, root)) + length = -1 + + while queue: + depth, node = queue.popleft() + + if length != depth: + length += 1 + result.append([]) + result[depth].append(node.val) + + if node.left is not None: + queue.append((depth + 1, node.left)) + if node.right is not None: + queue.append((depth + 1, node.right)) + + return result diff --git a/study-plan/leetcode-75/day6-n-ary-tree-preorder-traversal.py b/study-plan/leetcode-75/day6-n-ary-tree-preorder-traversal.py new file mode 100644 index 0000000..3ce0c1c --- /dev/null +++ b/study-plan/leetcode-75/day6-n-ary-tree-preorder-traversal.py @@ -0,0 +1,30 @@ +# https://leetcode.com/problems/n-ary-tree-preorder-traversal/ +# 589. N-ary Tree Preorder Traversal + +from typing import List +from common.leetcodeds import Node + + +class Solution: + def dfs(self, node, result): + + if node is None: + return + + result.append(node.val) + + if node.children is None: + return + + for child in node.children: + self.dfs(child, result) + + # TODO iteration 으로도 풀기 + def preorder(self, root: 'Node') -> List[int]: + if root is None: + return [] + + result = [root.val] + for node in root.children: + self.dfs(node, result) + return result diff --git a/study-plan/leetcode-75/day7-binary-search.py b/study-plan/leetcode-75/day7-binary-search.py new file mode 100644 index 0000000..f4205ed --- /dev/null +++ b/study-plan/leetcode-75/day7-binary-search.py @@ -0,0 +1,27 @@ +# https://leetcode.com/problems/binary-search/ +# 704. Binary Search +from typing import List + + +class Solution: + def search(self, nums: List[int], target: int) -> int: + result = -1 + + left, right = 0, len(nums) - 1 + + while left <= right: + mid = (left + right) // 2 + if nums[mid] < target: + left += 1 + elif nums[mid] > target: + right -= 1 + else: + return mid + + return result + + +if __name__ == '__main__': + sol = Solution() + print(sol.search([-1, 0, 3, 5, 9, 12], 9)) + print(sol.search([-1, 0, 3, 5, 9, 12], 2)) diff --git a/study-plan/leetcode-75/day7-first-bad-version.py b/study-plan/leetcode-75/day7-first-bad-version.py new file mode 100644 index 0000000..6343f79 --- /dev/null +++ b/study-plan/leetcode-75/day7-first-bad-version.py @@ -0,0 +1,24 @@ +# https://leetcode.com/problems/first-bad-version/ +# 278. First Bad Version + +# The isBadVersion API is already defined for you. +def isBadVersion(version: int) -> bool: + return version == 1702766719 + + +class Solution: + def firstBadVersion(self, n: int) -> int: + left, right = 1, n + while left <= right: + mid = (left + right) // 2 + if not isBadVersion(mid): + left = mid + 1 + else: + right = mid - 1 + + return left + + +if __name__ == '__main__': + sol = Solution() + print(sol.firstBadVersion(2126753390)) From bd5b7816ab90dd9d25a9f156a9fa682b09ad9030 Mon Sep 17 00:00:00 2001 From: iamminji Date: Thu, 1 Sep 2022 21:12:37 +0900 Subject: [PATCH 05/24] Rename challenge directory --- README.md | 36 +++++++++---------- challenge/2020/{july => 07}/3Sum.md | 0 challenge/2020/{july => 07}/3Sum.py | 0 challenge/2020/{july => 07}/Add_Binary.md | 0 challenge/2020/{july => 07}/Add_Binary.py | 0 .../All_Paths_From_Source_to_Target.py | 0 .../2020/{july => 07}/Arranging_Coins.md | 0 .../2020/{july => 07}/Arranging_Coins.py | 0 .../Binary_Tree_Level_Order_Traversal_II.md | 0 .../Binary_Tree_Level_Order_Traversal_II.py | 0 ...inary_Tree_Zigzag_Level_Order_Traversal.py | 0 ...Flatten_a_Multilevel_Doubly_Linked_List.md | 0 ...Flatten_a_Multilevel_Doubly_Linked_List.py | 0 .../2020/{july => 07}/Hamming_Distance.md | 0 .../2020/{july => 07}/Hamming_Distance.py | 0 .../2020/{july => 07}/Island_Perimeter.md | 0 .../2020/{july => 07}/Island_Perimeter.py | 0 challenge/2020/{july => 07}/Plus_One.md | 0 challenge/2020/{july => 07}/Plus_One.py | 0 .../{july => 07}/Prison_Cells_After_N_Days.md | 0 .../{july => 07}/Prison_Cells_After_N_Days.py | 0 .../Remove_Linked_List_Elements.py | 0 .../{july => 07}/Reverse_Words_in_a_String.py | 0 challenge/2020/{july => 07}/Same_Tree.py | 0 challenge/2020/{july => 07}/Subsets.py | 0 .../{july => 07}/Top_K_Frequent_Elements.py | 0 challenge/2020/{july => 07}/Ugly_Number_II.md | 0 challenge/2020/{july => 07}/Ugly_Number_II.py | 0 challenge/2020/{july => 07}/Word_Search.py | 0 29 files changed, 18 insertions(+), 18 deletions(-) rename challenge/2020/{july => 07}/3Sum.md (100%) rename challenge/2020/{july => 07}/3Sum.py (100%) rename challenge/2020/{july => 07}/Add_Binary.md (100%) rename challenge/2020/{july => 07}/Add_Binary.py (100%) rename challenge/2020/{july => 07}/All_Paths_From_Source_to_Target.py (100%) rename challenge/2020/{july => 07}/Arranging_Coins.md (100%) rename challenge/2020/{july => 07}/Arranging_Coins.py (100%) rename challenge/2020/{july => 07}/Binary_Tree_Level_Order_Traversal_II.md (100%) rename challenge/2020/{july => 07}/Binary_Tree_Level_Order_Traversal_II.py (100%) rename challenge/2020/{july => 07}/Binary_Tree_Zigzag_Level_Order_Traversal.py (100%) rename challenge/2020/{july => 07}/Flatten_a_Multilevel_Doubly_Linked_List.md (100%) rename challenge/2020/{july => 07}/Flatten_a_Multilevel_Doubly_Linked_List.py (100%) rename challenge/2020/{july => 07}/Hamming_Distance.md (100%) rename challenge/2020/{july => 07}/Hamming_Distance.py (100%) rename challenge/2020/{july => 07}/Island_Perimeter.md (100%) rename challenge/2020/{july => 07}/Island_Perimeter.py (100%) rename challenge/2020/{july => 07}/Plus_One.md (100%) rename challenge/2020/{july => 07}/Plus_One.py (100%) rename challenge/2020/{july => 07}/Prison_Cells_After_N_Days.md (100%) rename challenge/2020/{july => 07}/Prison_Cells_After_N_Days.py (100%) rename challenge/2020/{july => 07}/Remove_Linked_List_Elements.py (100%) rename challenge/2020/{july => 07}/Reverse_Words_in_a_String.py (100%) rename challenge/2020/{july => 07}/Same_Tree.py (100%) rename challenge/2020/{july => 07}/Subsets.py (100%) rename challenge/2020/{july => 07}/Top_K_Frequent_Elements.py (100%) rename challenge/2020/{july => 07}/Ugly_Number_II.md (100%) rename challenge/2020/{july => 07}/Ugly_Number_II.py (100%) rename challenge/2020/{july => 07}/Word_Search.py (100%) diff --git a/README.md b/README.md index d29e077..2239127 100644 --- a/README.md +++ b/README.md @@ -238,21 +238,21 @@ | title | code | solutions | |------------------------------------------------------|------------|----------------| -| [Arranging Coins](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3377/) | [python](challenge/2020/july/Arranging_Coins.py) | [solutions](challenge/2020/july/Arranging_Coins.md)| -| [Binary Tree Level Order Traversal II](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3378/) | [python](challenge/2020/july/Binary_Tree_Level_Order_Traversal_II.py) | [solutions](challenge/2020/july/Binary_Tree_Level_Order_Traversal_II.md)| -| [Prison Cells After N Days](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3379/) | [python](challenge/2020/july/Prison_Cells_After_N_Days.py) | [solutions](challenge/2020/july/Prison_Cells_After_N_Days.md)| -| [Ugly Number II](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3380/) | [python](challenge/2020/july/Ugly_Number_II.py) | [solutions](challenge/2020/july/Ugly_Number_II.md)| -| [Hamming Distance](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3381/) | [python](challenge/2020/july/Hamming_Distance.py) | [solutions](challenge/2020/july/Hamming_Distance.md)| -| [Plus One](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3382/) | [python](challenge/2020/july/Plus_One.py) | [solutions](challenge/2020/july/Plus_One.md)| -| [Island Perimeter](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3383/) | [python](challenge/2020/july/Island_Perimeter.py) | [solutions](challenge/2020/july/Island_Perimeter.md)| -| [Flatten a Multilevel Doubly Linked List](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3386/) | [python](challenge/2020/july/Flatten_a_Multilevel_Doubly_Linked_List.py) | [solutions](challenge/2020/july/Flatten_a_Multilevel_Doubly_Linked_List.md)| -| [Same Tree](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3389/) | [python](challenge/2020/july/Same_Tree.py) | | -| [3Sum](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3384/) | [python](challenge/2020/july/3Sum.py) | [solutions](challenge/2020/july/3Sum.md)| -| [Add Binary](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3395/) | [python](challenge/2020/july/Add_Binary.py) | [solution](challenge/2020/july/Add_Binary.md) | -| [Subsets](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3387/) | [python](challenge/2020/july/Subsets.py) | | -| [Reverse Words in a String](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3391/) | [python](challenge/2020/july/Reverse_Words_in_a_String.py) | | -| [Top K Frequent Elements](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3393/) | [python](challenge/2020/july/Top_K_Frequent_Elements.py) | | -| [Remove Linked List Elements](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3396/) | [python](challenge/2020/july/Remove_Linked_List_Elements.py) | | -| [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/547/week-4-july-22nd-july-28th/3398/) | [python](challenge/2020/july/Binary_Tree_Zigzag_Level_Order_Traversal.py) | | -| [Word Search](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3397/) | [python](challenge/2020/july/Word_Search.py) | | -| [All Paths From Source to Target](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/547/week-4-july-22nd-july-28th/3400/) | [python](challenge/2020/july/All_Paths_From_Source_to_Target.py) | | +| [Arranging Coins](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3377/) | [python](challenge/2020/07/Arranging_Coins.py) | [solutions](challenge/2020/07/Arranging_Coins.md)| +| [Binary Tree Level Order Traversal II](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3378/) | [python](challenge/2020/07/Binary_Tree_Level_Order_Traversal_II.py) | [solutions](challenge/2020/07/Binary_Tree_Level_Order_Traversal_II.md)| +| [Prison Cells After N Days](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3379/) | [python](challenge/2020/07/Prison_Cells_After_N_Days.py) | [solutions](challenge/2020/07/Prison_Cells_After_N_Days.md)| +| [Ugly Number II](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3380/) | [python](challenge/2020/07/Ugly_Number_II.py) | [solutions](challenge/2020/07/Ugly_Number_II.md)| +| [Hamming Distance](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3381/) | [python](challenge/2020/07/Hamming_Distance.py) | [solutions](challenge/2020/07/Hamming_Distance.md)| +| [Plus One](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3382/) | [python](challenge/2020/07/Plus_One.py) | [solutions](challenge/2020/07/Plus_One.md)| +| [Island Perimeter](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3383/) | [python](challenge/2020/07/Island_Perimeter.py) | [solutions](challenge/2020/07/Island_Perimeter.md)| +| [Flatten a Multilevel Doubly Linked List](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3386/) | [python](challenge/2020/07/Flatten_a_Multilevel_Doubly_Linked_List.py) | [solutions](challenge/2020/07/Flatten_a_Multilevel_Doubly_Linked_List.md)| +| [Same Tree](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3389/) | [python](challenge/2020/07/Same_Tree.py) | | +| [3Sum](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3384/) | [python](challenge/2020/07/3Sum.py) | [solutions](challenge/2020/07/3Sum.md)| +| [Add Binary](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3395/) | [python](challenge/2020/07/Add_Binary.py) | [solution](challenge/2020/07/Add_Binary.md) | +| [Subsets](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3387/) | [python](challenge/2020/07/Subsets.py) | | +| [Reverse Words in a String](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3391/) | [python](challenge/2020/07/Reverse_Words_in_a_String.py) | | +| [Top K Frequent Elements](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3393/) | [python](challenge/2020/07/Top_K_Frequent_Elements.py) | | +| [Remove Linked List Elements](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3396/) | [python](challenge/2020/07/Remove_Linked_List_Elements.py) | | +| [Binary Tree Zigzag Level Order Traversal](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/547/week-4-july-22nd-july-28th/3398/) | [python](challenge/2020/07/Binary_Tree_Zigzag_Level_Order_Traversal.py) | | +| [Word Search](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3397/) | [python](challenge/2020/07/Word_Search.py) | | +| [All Paths From Source to Target](https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/547/week-4-july-22nd-july-28th/3400/) | [python](challenge/2020/07/All_Paths_From_Source_to_Target.py) | | diff --git a/challenge/2020/july/3Sum.md b/challenge/2020/07/3Sum.md similarity index 100% rename from challenge/2020/july/3Sum.md rename to challenge/2020/07/3Sum.md diff --git a/challenge/2020/july/3Sum.py b/challenge/2020/07/3Sum.py similarity index 100% rename from challenge/2020/july/3Sum.py rename to challenge/2020/07/3Sum.py diff --git a/challenge/2020/july/Add_Binary.md b/challenge/2020/07/Add_Binary.md similarity index 100% rename from challenge/2020/july/Add_Binary.md rename to challenge/2020/07/Add_Binary.md diff --git a/challenge/2020/july/Add_Binary.py b/challenge/2020/07/Add_Binary.py similarity index 100% rename from challenge/2020/july/Add_Binary.py rename to challenge/2020/07/Add_Binary.py diff --git a/challenge/2020/july/All_Paths_From_Source_to_Target.py b/challenge/2020/07/All_Paths_From_Source_to_Target.py similarity index 100% rename from challenge/2020/july/All_Paths_From_Source_to_Target.py rename to challenge/2020/07/All_Paths_From_Source_to_Target.py diff --git a/challenge/2020/july/Arranging_Coins.md b/challenge/2020/07/Arranging_Coins.md similarity index 100% rename from challenge/2020/july/Arranging_Coins.md rename to challenge/2020/07/Arranging_Coins.md diff --git a/challenge/2020/july/Arranging_Coins.py b/challenge/2020/07/Arranging_Coins.py similarity index 100% rename from challenge/2020/july/Arranging_Coins.py rename to challenge/2020/07/Arranging_Coins.py diff --git a/challenge/2020/july/Binary_Tree_Level_Order_Traversal_II.md b/challenge/2020/07/Binary_Tree_Level_Order_Traversal_II.md similarity index 100% rename from challenge/2020/july/Binary_Tree_Level_Order_Traversal_II.md rename to challenge/2020/07/Binary_Tree_Level_Order_Traversal_II.md diff --git a/challenge/2020/july/Binary_Tree_Level_Order_Traversal_II.py b/challenge/2020/07/Binary_Tree_Level_Order_Traversal_II.py similarity index 100% rename from challenge/2020/july/Binary_Tree_Level_Order_Traversal_II.py rename to challenge/2020/07/Binary_Tree_Level_Order_Traversal_II.py diff --git a/challenge/2020/july/Binary_Tree_Zigzag_Level_Order_Traversal.py b/challenge/2020/07/Binary_Tree_Zigzag_Level_Order_Traversal.py similarity index 100% rename from challenge/2020/july/Binary_Tree_Zigzag_Level_Order_Traversal.py rename to challenge/2020/07/Binary_Tree_Zigzag_Level_Order_Traversal.py diff --git a/challenge/2020/july/Flatten_a_Multilevel_Doubly_Linked_List.md b/challenge/2020/07/Flatten_a_Multilevel_Doubly_Linked_List.md similarity index 100% rename from challenge/2020/july/Flatten_a_Multilevel_Doubly_Linked_List.md rename to challenge/2020/07/Flatten_a_Multilevel_Doubly_Linked_List.md diff --git a/challenge/2020/july/Flatten_a_Multilevel_Doubly_Linked_List.py b/challenge/2020/07/Flatten_a_Multilevel_Doubly_Linked_List.py similarity index 100% rename from challenge/2020/july/Flatten_a_Multilevel_Doubly_Linked_List.py rename to challenge/2020/07/Flatten_a_Multilevel_Doubly_Linked_List.py diff --git a/challenge/2020/july/Hamming_Distance.md b/challenge/2020/07/Hamming_Distance.md similarity index 100% rename from challenge/2020/july/Hamming_Distance.md rename to challenge/2020/07/Hamming_Distance.md diff --git a/challenge/2020/july/Hamming_Distance.py b/challenge/2020/07/Hamming_Distance.py similarity index 100% rename from challenge/2020/july/Hamming_Distance.py rename to challenge/2020/07/Hamming_Distance.py diff --git a/challenge/2020/july/Island_Perimeter.md b/challenge/2020/07/Island_Perimeter.md similarity index 100% rename from challenge/2020/july/Island_Perimeter.md rename to challenge/2020/07/Island_Perimeter.md diff --git a/challenge/2020/july/Island_Perimeter.py b/challenge/2020/07/Island_Perimeter.py similarity index 100% rename from challenge/2020/july/Island_Perimeter.py rename to challenge/2020/07/Island_Perimeter.py diff --git a/challenge/2020/july/Plus_One.md b/challenge/2020/07/Plus_One.md similarity index 100% rename from challenge/2020/july/Plus_One.md rename to challenge/2020/07/Plus_One.md diff --git a/challenge/2020/july/Plus_One.py b/challenge/2020/07/Plus_One.py similarity index 100% rename from challenge/2020/july/Plus_One.py rename to challenge/2020/07/Plus_One.py diff --git a/challenge/2020/july/Prison_Cells_After_N_Days.md b/challenge/2020/07/Prison_Cells_After_N_Days.md similarity index 100% rename from challenge/2020/july/Prison_Cells_After_N_Days.md rename to challenge/2020/07/Prison_Cells_After_N_Days.md diff --git a/challenge/2020/july/Prison_Cells_After_N_Days.py b/challenge/2020/07/Prison_Cells_After_N_Days.py similarity index 100% rename from challenge/2020/july/Prison_Cells_After_N_Days.py rename to challenge/2020/07/Prison_Cells_After_N_Days.py diff --git a/challenge/2020/july/Remove_Linked_List_Elements.py b/challenge/2020/07/Remove_Linked_List_Elements.py similarity index 100% rename from challenge/2020/july/Remove_Linked_List_Elements.py rename to challenge/2020/07/Remove_Linked_List_Elements.py diff --git a/challenge/2020/july/Reverse_Words_in_a_String.py b/challenge/2020/07/Reverse_Words_in_a_String.py similarity index 100% rename from challenge/2020/july/Reverse_Words_in_a_String.py rename to challenge/2020/07/Reverse_Words_in_a_String.py diff --git a/challenge/2020/july/Same_Tree.py b/challenge/2020/07/Same_Tree.py similarity index 100% rename from challenge/2020/july/Same_Tree.py rename to challenge/2020/07/Same_Tree.py diff --git a/challenge/2020/july/Subsets.py b/challenge/2020/07/Subsets.py similarity index 100% rename from challenge/2020/july/Subsets.py rename to challenge/2020/07/Subsets.py diff --git a/challenge/2020/july/Top_K_Frequent_Elements.py b/challenge/2020/07/Top_K_Frequent_Elements.py similarity index 100% rename from challenge/2020/july/Top_K_Frequent_Elements.py rename to challenge/2020/07/Top_K_Frequent_Elements.py diff --git a/challenge/2020/july/Ugly_Number_II.md b/challenge/2020/07/Ugly_Number_II.md similarity index 100% rename from challenge/2020/july/Ugly_Number_II.md rename to challenge/2020/07/Ugly_Number_II.md diff --git a/challenge/2020/july/Ugly_Number_II.py b/challenge/2020/07/Ugly_Number_II.py similarity index 100% rename from challenge/2020/july/Ugly_Number_II.py rename to challenge/2020/07/Ugly_Number_II.py diff --git a/challenge/2020/july/Word_Search.py b/challenge/2020/07/Word_Search.py similarity index 100% rename from challenge/2020/july/Word_Search.py rename to challenge/2020/07/Word_Search.py From aa5c48561d8aaa2ff91afb998255e5a5cc03ebc7 Mon Sep 17 00:00:00 2001 From: iamminji Date: Thu, 1 Sep 2022 21:16:01 +0900 Subject: [PATCH 06/24] =?UTF-8?q?[20220901]=209=EC=9B=94=201=EC=9D=BC=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../09/01-count-good-nodes-in-binary-tree.py | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 challenge/2022/09/01-count-good-nodes-in-binary-tree.py diff --git a/challenge/2022/09/01-count-good-nodes-in-binary-tree.py b/challenge/2022/09/01-count-good-nodes-in-binary-tree.py new file mode 100644 index 0000000..3ccbb3c --- /dev/null +++ b/challenge/2022/09/01-count-good-nodes-in-binary-tree.py @@ -0,0 +1,33 @@ +# https://leetcode.com/problems/count-good-nodes-in-binary-tree/ +# 1448. Count Good Nodes in Binary Tree + + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + + +from collections import deque + + +class Solution: + def goodNodes(self, root: TreeNode) -> int: + queue = deque() + queue.append((root.val, root)) + + result = 0 + while queue: + mx, node = queue.popleft() + if node.val >= mx: + result += 1 + + if node.left is not None: + queue.append((max(mx, node.val), node.left)) + + if node.right is not None: + queue.append((max(mx, node.val), node.right)) + + return result From 491aa72f3f2dfc15d12d9d5275a510849f2bf74b Mon Sep 17 00:00:00 2001 From: iamminji Date: Fri, 2 Sep 2022 22:07:10 +0900 Subject: [PATCH 07/24] =?UTF-8?q?[20220902]=209=EC=9B=94=202=EC=9D=BC=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../09/02-average-of-levels-in-binary-tree.py | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 challenge/2022/09/02-average-of-levels-in-binary-tree.py diff --git a/challenge/2022/09/02-average-of-levels-in-binary-tree.py b/challenge/2022/09/02-average-of-levels-in-binary-tree.py new file mode 100644 index 0000000..289c011 --- /dev/null +++ b/challenge/2022/09/02-average-of-levels-in-binary-tree.py @@ -0,0 +1,33 @@ +# https://leetcode.com/problems/average-of-levels-in-binary-tree/ +# 637. Average of Levels in Binary Tree + +from typing import Optional, List +from common.leetcodeds import TreeNode +from collections import deque, defaultdict + + +class Solution: + def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: + queue = deque() + queue.append((0, root)) + result = [] + count = defaultdict(int) + + while queue: + depth, node = queue.popleft() + if depth >= len(result): + result.append(node.val) + else: + result[depth] += node.val + + count[depth] += 1 + + if node.left is not None: + queue.append((depth + 1, node.left)) + if node.right is not None: + queue.append((depth + 1, node.right)) + + for idx in range(len(result)): + result[idx] /= count[idx] + + return result From 5272e5ebbeea25425cf9a3296a6c67326e00124c Mon Sep 17 00:00:00 2001 From: iamminji Date: Thu, 10 Nov 2022 23:02:36 +0900 Subject: [PATCH 08/24] [20221110] solve the easy problem with rust --- .../build-array-from-permutation.rs" | 9 +++++++++ .../concatenation-of-array.rs" | 11 +++++++++++ 2 files changed, 20 insertions(+) create mode 100644 "\360\237\231\202easy/1920.Build-Array-from-Permutation/build-array-from-permutation.rs" create mode 100644 "\360\237\231\202easy/1929.Concatenation-of-Array/concatenation-of-array.rs" diff --git "a/\360\237\231\202easy/1920.Build-Array-from-Permutation/build-array-from-permutation.rs" "b/\360\237\231\202easy/1920.Build-Array-from-Permutation/build-array-from-permutation.rs" new file mode 100644 index 0000000..fb90791 --- /dev/null +++ "b/\360\237\231\202easy/1920.Build-Array-from-Permutation/build-array-from-permutation.rs" @@ -0,0 +1,9 @@ +impl Solution { + pub fn build_array(nums: Vec) -> Vec { + let mut result: Vec = Vec::with_capacity(nums.len()); + for i in 0..nums.len() as usize { + result.push(nums[nums[i] as usize]); + } + result + } +} diff --git "a/\360\237\231\202easy/1929.Concatenation-of-Array/concatenation-of-array.rs" "b/\360\237\231\202easy/1929.Concatenation-of-Array/concatenation-of-array.rs" new file mode 100644 index 0000000..ce21928 --- /dev/null +++ "b/\360\237\231\202easy/1929.Concatenation-of-Array/concatenation-of-array.rs" @@ -0,0 +1,11 @@ +impl Solution { + pub fn get_concatenation(nums: Vec) -> Vec { + let mut result = Vec::new(); + for i in 0..2 { + for num in &nums { + result.push(*num); + } + } + result + } +} From e0874d6e2f033d6f5963a3e6686b2e101319f309 Mon Sep 17 00:00:00 2001 From: iamminji Date: Mon, 2 Jan 2023 21:19:54 +0900 Subject: [PATCH 09/24] [20230102] solve medium problem --- .../add_two_numbers_2.py" | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 "\360\237\244\224medium/0002.Add-Two-Numbers/add_two_numbers_2.py" diff --git "a/\360\237\244\224medium/0002.Add-Two-Numbers/add_two_numbers_2.py" "b/\360\237\244\224medium/0002.Add-Two-Numbers/add_two_numbers_2.py" new file mode 100644 index 0000000..d89f2ce --- /dev/null +++ "b/\360\237\244\224medium/0002.Add-Two-Numbers/add_two_numbers_2.py" @@ -0,0 +1,37 @@ +# 2. Add Two Numbers +# https://leetcode.com/problems/add-two-numbers/ + +from typing import Optional + +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: + c = 0 + result = ListNode(0) + dummy = result + while l1 is not None or l2 is not None: + lv1 = l1.val if l1 is not None else 0 + lv2 = l2.val if l2 is not None else 0 + + r = (lv1 + lv2 + c) % 10 + c = (lv1 + lv2 + c) // 10 + + dummy.next = ListNode(r) + + if l1 is not None: + l1 = l1.next + if l2 is not None: + l2 = l2.next + + dummy = dummy.next + + if c > 0: + dummy.next = ListNode(c) + + return result.next From 2f2dcb68b5a226106f89be240cd2fd59d1973180 Mon Sep 17 00:00:00 2001 From: iaminji Date: Mon, 2 Jan 2023 21:21:35 +0900 Subject: [PATCH 10/24] [20230102] solve medium problem --- .../0002.Add-Two-Numbers/add_two_numbers_2.py" | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git "a/\360\237\244\224medium/0002.Add-Two-Numbers/add_two_numbers_2.py" "b/\360\237\244\224medium/0002.Add-Two-Numbers/add_two_numbers_2.py" index d89f2ce..bfaa818 100644 --- "a/\360\237\244\224medium/0002.Add-Two-Numbers/add_two_numbers_2.py" +++ "b/\360\237\244\224medium/0002.Add-Two-Numbers/add_two_numbers_2.py" @@ -3,6 +3,7 @@ from typing import Optional + # Definition for singly-linked list. class ListNode: def __init__(self, x): @@ -19,8 +20,8 @@ def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optio lv1 = l1.val if l1 is not None else 0 lv2 = l2.val if l2 is not None else 0 - r = (lv1 + lv2 + c) % 10 - c = (lv1 + lv2 + c) // 10 + v = lv1 + lv2 + c + c, r = v // 10, v % 10 dummy.next = ListNode(r) From 82416faf94f5373afd10445049e5044e26b11ff7 Mon Sep 17 00:00:00 2001 From: iaminji Date: Wed, 4 Jan 2023 22:51:51 +0900 Subject: [PATCH 11/24] [20230104] solve medium problem --- .../minimum-rounds-to-complete-all-tasks.py" | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 "\360\237\244\224medium/2244.Minimum-Rounds-to-Complete-All-Tasks/minimum-rounds-to-complete-all-tasks.py" diff --git "a/\360\237\244\224medium/2244.Minimum-Rounds-to-Complete-All-Tasks/minimum-rounds-to-complete-all-tasks.py" "b/\360\237\244\224medium/2244.Minimum-Rounds-to-Complete-All-Tasks/minimum-rounds-to-complete-all-tasks.py" new file mode 100644 index 0000000..8d59e98 --- /dev/null +++ "b/\360\237\244\224medium/2244.Minimum-Rounds-to-Complete-All-Tasks/minimum-rounds-to-complete-all-tasks.py" @@ -0,0 +1,24 @@ +# 2244. Minimum Rounds to Complete All Tasks +# https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/ + +from typing import List +from collections import Counter + + +class Solution: + def minimumRounds(self, tasks: List[int]) -> int: + t = Counter(tasks) + res = 0 + for _, count in t.items(): + if count == 1: + return -1 + if count % 3 == 0: + res += count // 3 + else: + res += count // 3 + 1 + return res + + +if __name__ == '__main__': + sol = Solution() + print(sol.minimumRounds([1 for _ in range(16)])) From dcb8a96c40f19513b122de6108cd6f6c8c9532e0 Mon Sep 17 00:00:00 2001 From: iaminji Date: Thu, 5 Jan 2023 20:23:33 +0900 Subject: [PATCH 12/24] [20230105] Add comment --- .../minimum-rounds-to-complete-all-tasks.py" | 5 +++++ 1 file changed, 5 insertions(+) diff --git "a/\360\237\244\224medium/2244.Minimum-Rounds-to-Complete-All-Tasks/minimum-rounds-to-complete-all-tasks.py" "b/\360\237\244\224medium/2244.Minimum-Rounds-to-Complete-All-Tasks/minimum-rounds-to-complete-all-tasks.py" index 8d59e98..32bc653 100644 --- "a/\360\237\244\224medium/2244.Minimum-Rounds-to-Complete-All-Tasks/minimum-rounds-to-complete-all-tasks.py" +++ "b/\360\237\244\224medium/2244.Minimum-Rounds-to-Complete-All-Tasks/minimum-rounds-to-complete-all-tasks.py" @@ -15,6 +15,11 @@ def minimumRounds(self, tasks: List[int]) -> int: if count % 3 == 0: res += count // 3 else: + # +1 을 해주는 이유는 + # 3으로 나누어 떨어지지 않는 경우 3K + 1, 3K + 2 가 있다. + # 3K + 2 는 3K + 2 * 1 과 같음 ==> 따라서 K + 1 + # 3K + 1 은 3(K-1) + 4 = 3(K-1) + 2 * 2 와 같음 ==> K - 1 + 2 ==> K + 1 + # K 가 어떤 값이든 + 1 을 해주면 됨 res += count // 3 + 1 return res From 35ce63ed2e4b59b2564c5399e16cde1a126c8790 Mon Sep 17 00:00:00 2001 From: iaminji Date: Thu, 5 Jan 2023 21:31:14 +0900 Subject: [PATCH 13/24] [20230105] Solve medium problem --- ...mum-number-of-arrows-to-burst-balloons.py" | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 "\360\237\244\224medium/0452.Minimum-Number-of-Arrows-to-Burst-Balloons/minimum-number-of-arrows-to-burst-balloons.py" diff --git "a/\360\237\244\224medium/0452.Minimum-Number-of-Arrows-to-Burst-Balloons/minimum-number-of-arrows-to-burst-balloons.py" "b/\360\237\244\224medium/0452.Minimum-Number-of-Arrows-to-Burst-Balloons/minimum-number-of-arrows-to-burst-balloons.py" new file mode 100644 index 0000000..0d6cc4b --- /dev/null +++ "b/\360\237\244\224medium/0452.Minimum-Number-of-Arrows-to-Burst-Balloons/minimum-number-of-arrows-to-burst-balloons.py" @@ -0,0 +1,30 @@ +# 452. Minimum Number of Arrows to Burst Balloons +# https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ + +from typing import List + + +class Solution: + def findMinArrowShots(self, points: List[List[int]]) -> int: + # point 값이 최소 1개 이상 있어서 + # 무조건 한개의 화살을 쏘게 되어 있음 + result = 1 + + # 풍선의 끝점으로 정렬함 + points.sort(key=lambda x: x[1]) + prev = points[0] + for point in points: + # 풍선이 서로 안 닿아 있음 + # 그러면 다음 풍선을 burst 하기 위해 화살을 쏜다 + if prev[1] < point[0]: + result += 1 + prev = point + # else 라면 닿아 있다는 의미 이므로 + # 화살을 쏠 필요가 없다. (이미 prev 풍선 확인 하면서 쐈기 때문임) + + return result + + +if __name__ == '__main__': + sol = Solution() + print(sol.findMinArrowShots([[10, 16], [2, 8], [1, 6], [7, 12]])) From b9a3169bcbffe6b1026143567ba67f63fd0995f8 Mon Sep 17 00:00:00 2001 From: iaminji Date: Tue, 11 Apr 2023 23:22:31 +0900 Subject: [PATCH 14/24] [20230411] Solve easy problem --- .../sort_array_by_parity.py" | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 "\360\237\231\202easy/0905.Sort-Array-By-Parity/sort_array_by_parity.py" diff --git "a/\360\237\231\202easy/0905.Sort-Array-By-Parity/sort_array_by_parity.py" "b/\360\237\231\202easy/0905.Sort-Array-By-Parity/sort_array_by_parity.py" new file mode 100644 index 0000000..fbbe0a0 --- /dev/null +++ "b/\360\237\231\202easy/0905.Sort-Array-By-Parity/sort_array_by_parity.py" @@ -0,0 +1,16 @@ +# 905. Sort Array By Parity +# https://leetcode.com/problems/sort-array-by-parity/description/ + +from typing import List + + +class Solution: + def sortArrayByParity(self, nums: List[int]) -> List[int]: + i, j = 0, len(nums) - 1 + while i < j: + if nums[i] % 2 != 0: + nums[i], nums[j] = nums[j], nums[i] + j -= 1 + else: + i += 1 + return nums From 2f50e4bbb6db351c357ed2821dc9e768623eb651 Mon Sep 17 00:00:00 2001 From: iaminji Date: Wed, 12 Apr 2023 22:25:11 +0900 Subject: [PATCH 15/24] [20230412] Solve easy problem --- README.md | 2 ++ ...ort_even_and_odd_indices_independently.py" | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 "\360\237\231\202easy/2164.Sort-Even-and-Odd-Indices-Independently/sort_even_and_odd_indices_independently.py" diff --git a/README.md b/README.md index 2239127..6c6d875 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com) +> 🫠 NO MORE UPDATE README.md + ## Problems | # | title | difficulty | languages | tag | diff --git "a/\360\237\231\202easy/2164.Sort-Even-and-Odd-Indices-Independently/sort_even_and_odd_indices_independently.py" "b/\360\237\231\202easy/2164.Sort-Even-and-Odd-Indices-Independently/sort_even_and_odd_indices_independently.py" new file mode 100644 index 0000000..6180ad1 --- /dev/null +++ "b/\360\237\231\202easy/2164.Sort-Even-and-Odd-Indices-Independently/sort_even_and_odd_indices_independently.py" @@ -0,0 +1,33 @@ +# 2164. Sort Even and Odd Indices Independently +# https://leetcode.com/problems/sort-even-and-odd-indices-independently/description/ +from typing import List + + +class Solution: + def sortEvenOdd(self, nums: List[int]) -> List[int]: + even_nums = [] + odd_nums = [] + + for i in range(len(nums)): + if i % 2 == 0: + even_nums.append(nums[i]) + else: + odd_nums.append(nums[i]) + + even_nums.sort() + odd_nums.sort(reverse=True) + + i, j = 0, 0 + k = 0 + result = [0 for _ in range(len(nums))] + while i < len(even_nums): + result[k] = even_nums[i] + i += 1 + k += 2 + + k = 1 + while j < len(odd_nums): + result[k] = odd_nums[j] + j += 1 + k += 2 + return result From 51857abc9972053c275b98b2dd7e4b6a946c63cc Mon Sep 17 00:00:00 2001 From: iamminji Date: Sat, 15 Apr 2023 21:20:57 +0900 Subject: [PATCH 16/24] [20230415] Solve easy problem --- .../roman_to_integer_2.py" | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 "\360\237\231\202easy/0013.Roman-to-Integer/roman_to_integer_2.py" diff --git "a/\360\237\231\202easy/0013.Roman-to-Integer/roman_to_integer_2.py" "b/\360\237\231\202easy/0013.Roman-to-Integer/roman_to_integer_2.py" new file mode 100644 index 0000000..73fc9e6 --- /dev/null +++ "b/\360\237\231\202easy/0013.Roman-to-Integer/roman_to_integer_2.py" @@ -0,0 +1,31 @@ +# 13. Roman to Integer +# https://leetcode.com/problems/roman-to-integer/description/ + + +class Solution: + def romanToInt(self, s: str) -> int: + d = {'I' : 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} + + i = 0 + result = 0 + + while i < len(s) - 1: + c = s[i] + if c == 'I' and (s[i+1] == 'V' or s[i+1] == 'X'): + result += d[s[i+1]] - 1 + i += 2 + continue + elif c == 'X' and (s[i+1] == 'L' or s[i+1] == 'C'): + result += d[s[i+1]] - 10 + i += 2 + continue + elif c == 'C' and (s[i+1] == 'D' or s[i+1] == 'M'): + result += d[s[i+1]] - 100 + i += 2 + continue + result += d[c] + i += 1 + + if i <= len(s) - 1: + result += d[s[i]] + return result From 2166db08f2ae2746305bfb382a2ea4c70e38482a Mon Sep 17 00:00:00 2001 From: iamminji Date: Sun, 16 Apr 2023 20:52:32 +0900 Subject: [PATCH 17/24] [20230416] Solve Binary Search problems --- .../search_insert_position_2.py" | 24 +++++++++++++ ...st_position_of_element_in_sorted_array.py" | 36 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 "\360\237\231\202easy/0035.Search-Insert-Position/search_insert_position_2.py" create mode 100644 "\360\237\244\224medium/0034.Find-First-and-Last-Position-of-Element-in-Sorted-Array/find_first_and_last_position_of_element_in_sorted_array.py" diff --git "a/\360\237\231\202easy/0035.Search-Insert-Position/search_insert_position_2.py" "b/\360\237\231\202easy/0035.Search-Insert-Position/search_insert_position_2.py" new file mode 100644 index 0000000..51b2043 --- /dev/null +++ "b/\360\237\231\202easy/0035.Search-Insert-Position/search_insert_position_2.py" @@ -0,0 +1,24 @@ +# 35. Search Insert Position +# https://leetcode.com/problems/search-insert-position/ +from typing import List + + +class Solution: + # 문제 조건이 O(logn) 이기 때문에 Binary Search 관련 문제라는 것을 알 수 있다. (+ 이미 정렬된 nums) + def searchInsert(self, nums: List[int], target: int) -> int: + + start, end = 0, len(nums) - 1 + + while start <= end: + mid = (start + end) // 2 + if nums[mid] < target: + start = mid + 1 + elif nums[mid] > target: + end = mid - 1 + else: + return mid + + # target 이 들어갈 포지션은 이전 값 보다 크고 다음 값 보다 작은 곳이다. + # while 문 벗어났다는 건 start > end 라는 의미다. + # 따라서 이 포지션 값은 start 와 같다 + return start diff --git "a/\360\237\244\224medium/0034.Find-First-and-Last-Position-of-Element-in-Sorted-Array/find_first_and_last_position_of_element_in_sorted_array.py" "b/\360\237\244\224medium/0034.Find-First-and-Last-Position-of-Element-in-Sorted-Array/find_first_and_last_position_of_element_in_sorted_array.py" new file mode 100644 index 0000000..5d99295 --- /dev/null +++ "b/\360\237\244\224medium/0034.Find-First-and-Last-Position-of-Element-in-Sorted-Array/find_first_and_last_position_of_element_in_sorted_array.py" @@ -0,0 +1,36 @@ +# 34. Find First and Last Position of Element in Sorted Array +# https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/ +from typing import List + + +class Solution: + def searchRange(self, nums: List[int], target: int) -> List[int]: + start, end = 0, len(nums) - 1 + + pos = [10 ** 9 + 1, -(10 ** 9) - 1] + while start <= end: + mid = (start + end) // 2 + if nums[mid] < target: + start = mid + 1 + elif nums[mid] > target: + end = mid - 1 + else: + pos[0] = min(pos[0], mid) + pos[1] = max(pos[1], mid) + start += 1 + + start, end = 0, len(nums) - 1 + while start <= end: + mid = (start + end) // 2 + if nums[mid] < target: + start = mid + 1 + elif nums[mid] > target: + end = mid - 1 + else: + pos[0] = min(pos[0], mid) + pos[1] = max(pos[1], mid) + end -= 1 + + if pos == [10 ** 9 + 1, -(10 ** 9) - 1]: + return [-1, -1] + return pos From f2bbe93873fb5c9e84d73c86f10c6c04fe490962 Mon Sep 17 00:00:00 2001 From: iaminji Date: Tue, 18 Apr 2023 07:45:25 +0900 Subject: [PATCH 18/24] [20230418] Solve medium problem --- .../search_in_rotated_sorted_array_2.py" | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 "\360\237\244\224medium/0033.Search-in-Rotated-Sorted-Array/search_in_rotated_sorted_array_2.py" diff --git "a/\360\237\244\224medium/0033.Search-in-Rotated-Sorted-Array/search_in_rotated_sorted_array_2.py" "b/\360\237\244\224medium/0033.Search-in-Rotated-Sorted-Array/search_in_rotated_sorted_array_2.py" new file mode 100644 index 0000000..c80f192 --- /dev/null +++ "b/\360\237\244\224medium/0033.Search-in-Rotated-Sorted-Array/search_in_rotated_sorted_array_2.py" @@ -0,0 +1,38 @@ +# 33. Search in Rotated Sorted Array +# https://leetcode.com/problems/search-in-rotated-sorted-array/description/ +from typing import List + + +class Solution: + def search(self, nums: List[int], target: int) -> int: + + start, end = 0, len(nums) - 1 + while start <= end: + mid = (start + end) // 2 + if nums[mid] == target: + return mid + elif nums[mid] < target: # 찾는 값이 우측에 있을 때 + # start 값이 mid 보다 크다면 rotation 되었다. + # 찾는 값이 end 보다 크다면 우측에 target 없음. 이 값은 rotation 되었기 때문에 좌측에 있다. + if nums[start] > nums[mid] and nums[end] < target: + end = mid - 1 + else: + # 일반적인 Binary Search 다.start 값을 증가시킨다. + start = mid + 1 + else: # 찾는 값이 왼쪽에 있을 때 + # mid 값이 end 보다 크다면 rotation 되었다. + # 찾는 값이 start 보다 작다면 좌측에 없음. 이 값은 rotation 되었기 때문에 우측에 있다. + if nums[mid] > nums[end] and nums[start] > target: + start = mid + 1 + else: + # 일반적인 Binary Search 다. end 값을 감소시킨다. + end = mid - 1 + + return -1 + + +if __name__ == "__main__": + sol = Solution() + print(sol.search([4, 5, 6, 7, 0, 1, 2, 3], 0)) + print(sol.search([3, 5, 1], 3)) + print(sol.search([5, 6, 7, 1, 2, 3, 4], 5)) From bb509ef09b66b275cc33b73448b2a158bcf4d55b Mon Sep 17 00:00:00 2001 From: iamminji Date: Mon, 1 May 2023 16:09:27 +0900 Subject: [PATCH 19/24] [20230501] Solve Binary Search problems --- ...ind-target-indices-after-sorting-array.py" | 22 ++++++++++++++++ .../peak-index-in-a-mountain-array.py" | 26 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 "\360\237\231\202easy/2089.Find-Target-Indices-After-Sorting-Array/find-target-indices-after-sorting-array.py" create mode 100644 "\360\237\244\224medium/0852.Peak-Index-in-a-Mountain-Array/peak-index-in-a-mountain-array.py" diff --git "a/\360\237\231\202easy/2089.Find-Target-Indices-After-Sorting-Array/find-target-indices-after-sorting-array.py" "b/\360\237\231\202easy/2089.Find-Target-Indices-After-Sorting-Array/find-target-indices-after-sorting-array.py" new file mode 100644 index 0000000..b8d091e --- /dev/null +++ "b/\360\237\231\202easy/2089.Find-Target-Indices-After-Sorting-Array/find-target-indices-after-sorting-array.py" @@ -0,0 +1,22 @@ +# 2089. Find Target Indices After Sorting Array +# https://leetcode.com/problems/find-target-indices-after-sorting-array/ + +from typing import List + + +class Solution: + def targetIndices(self, nums: List[int], target: int) -> List[int]: + m_cnt = 0 + t_cnt = 0 + + for num in nums: + if num < target: + m_cnt += 1 + if num == target: + t_cnt += 1 + + result = [] + for i in range(t_cnt): + result.append(m_cnt + i) + + return result diff --git "a/\360\237\244\224medium/0852.Peak-Index-in-a-Mountain-Array/peak-index-in-a-mountain-array.py" "b/\360\237\244\224medium/0852.Peak-Index-in-a-Mountain-Array/peak-index-in-a-mountain-array.py" new file mode 100644 index 0000000..53b96f1 --- /dev/null +++ "b/\360\237\244\224medium/0852.Peak-Index-in-a-Mountain-Array/peak-index-in-a-mountain-array.py" @@ -0,0 +1,26 @@ +# 852. Peak Index in a Mountain Array +# https://leetcode.com/problems/peak-index-in-a-mountain-array/description/ + +from typing import List + + +class Solution: + def peakIndexInMountainArray(self, arr: List[int]) -> int: + start, end = 0, len(arr) - 1 + while start <= end: + mid = (start + end) // 2 + if arr[mid - 1] < arr[mid] and arr[mid + 1] < arr[mid]: + return mid + if arr[mid-1] < arr[mid]: + start = mid + else: + end = mid + return 0 + + +if __name__ == '__main__': + sol = Solution() + # print(sol.peakIndexInMountainArray([3, 4, 5, 1])) + # print(sol.peakIndexInMountainArray([3, 5, 3, 2, 0])) + print(sol.peakIndexInMountainArray([24, 69, 100, 99, 79, 78, 67, 36, 26, 19])) + print(sol.peakIndexInMountainArray([8, 18, 24, 31, 37, 42, 43, 56, 65, 73, 93, 98, 100, 98, 76, 72, 69, 24, 23])) From a1d2939f317b65bbff187d28464bd5ec9dc4c0b0 Mon Sep 17 00:00:00 2001 From: iamminji Date: Tue, 2 May 2023 20:57:46 +0900 Subject: [PATCH 20/24] [20230502] Solve Binary Search problems --- .../search-in-rotated-sorted-array-ii.py" | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 "\360\237\244\224medium/0081.Search-in-Rotated-Sorted-Array-II/search-in-rotated-sorted-array-ii.py" diff --git "a/\360\237\244\224medium/0081.Search-in-Rotated-Sorted-Array-II/search-in-rotated-sorted-array-ii.py" "b/\360\237\244\224medium/0081.Search-in-Rotated-Sorted-Array-II/search-in-rotated-sorted-array-ii.py" new file mode 100644 index 0000000..2161059 --- /dev/null +++ "b/\360\237\244\224medium/0081.Search-in-Rotated-Sorted-Array-II/search-in-rotated-sorted-array-ii.py" @@ -0,0 +1,50 @@ +# 81. Search in Rotated Sorted Array II +# https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/ + +from typing import List + + +class Solution: + def search(self, nums: List[int], target: int) -> bool: + + start, end = 0, len(nums) - 1 + + while start <= end: + + while start < end and nums[start] == nums[start + 1]: + if nums[start] == target: + return True + start += 1 + + while start < end and nums[end] == nums[end - 1]: + if nums[end] == target: + return True + end -= 1 + + mid = (start + end) // 2 + + if nums[mid] == target: + return True + + if nums[start] <= nums[mid]: + if nums[start] <= target < nums[mid]: + end = mid - 1 + else: + start = mid + 1 + else: + if nums[mid] < target <= nums[end]: + start = mid + 1 + else: + end = mid - 1 + + return False + + +if __name__ == '__main__': + sol = Solution() + print(sol.search([1, 0, 1, 1, 1], 0)) + print(sol.search([2, 5, 6, 0, 0, 1, 2], 3)) + print(sol.search([1, 1, 1, 1, 1, 1, 1, 1, 1, 13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 13)) + print(sol.search([6, 1, 2, 4, 5], 1)) + print(sol.search([4, 5, 6, 7, 0, 1, 2], 0)) + print(sol.search([1, 3, 5], 1)) From 7d888f5a51f105585e114e741a1e7fd0555fbc80 Mon Sep 17 00:00:00 2001 From: iaminji Date: Wed, 3 May 2023 22:21:38 +0900 Subject: [PATCH 21/24] [20230503] Solve easy problem --- .../first-bad-version.py" | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 "\360\237\231\202easy/0278.First-Bad-Version/first-bad-version.py" diff --git "a/\360\237\231\202easy/0278.First-Bad-Version/first-bad-version.py" "b/\360\237\231\202easy/0278.First-Bad-Version/first-bad-version.py" new file mode 100644 index 0000000..6aa48a9 --- /dev/null +++ "b/\360\237\231\202easy/0278.First-Bad-Version/first-bad-version.py" @@ -0,0 +1,27 @@ +# https://leetcode.com/problems/first-bad-version/description/ +# 278. First Bad Version + + +# The isBadVersion API is already defined for you. +# def isBadVersion(version: int) -> bool: + +class Solution: + def firstBadVersion(self, n: int) -> int: + + start, end = 1, n + result = float("inf") + + while start <= end: + mid = (start + end) // 2 + if not isBadVersion(mid): + start = mid + 1 + else: + result = min(result, mid) + end = mid - 1 + return result + + +def isBadVersion(version) -> bool: + # 이미 Leetcode가 구현해서 구현할 필요가 없음 + # 런타임 에러 때문에 만들어둠 + pass From af5c50a021bef7bd13ec41fdfb85638621a72adc Mon Sep 17 00:00:00 2001 From: iamminji Date: Sun, 7 May 2023 14:37:13 +0900 Subject: [PATCH 22/24] [20230507] Solve BitManipulation easy problems --- .../0191.Number-of-1-Bits/number-of-1-bits.py" | 13 +++++++++++++ .../0231.Power-of-Two/power-of-two.py" | 12 ++++++++++++ .../xor-operation-in-an-array.py" | 11 +++++++++++ .../decode-xored-array.py" | 15 +++++++++++++++ 4 files changed, 51 insertions(+) create mode 100644 "\360\237\231\202easy/0191.Number-of-1-Bits/number-of-1-bits.py" create mode 100644 "\360\237\231\202easy/0231.Power-of-Two/power-of-two.py" create mode 100644 "\360\237\231\202easy/1486.XOR-Operation-in-an-Array/xor-operation-in-an-array.py" create mode 100644 "\360\237\231\202easy/1720.Decode-XORed-Array/decode-xored-array.py" diff --git "a/\360\237\231\202easy/0191.Number-of-1-Bits/number-of-1-bits.py" "b/\360\237\231\202easy/0191.Number-of-1-Bits/number-of-1-bits.py" new file mode 100644 index 0000000..d3d9a66 --- /dev/null +++ "b/\360\237\231\202easy/0191.Number-of-1-Bits/number-of-1-bits.py" @@ -0,0 +1,13 @@ +# 191. Number of 1 Bits +# https://leetcode.com/problems/number-of-1-bits/description/ + +class Solution: + def hammingWeight(self, n: int) -> int: + i = 0 + count = 0 + while i < 32: + if n & 1 == 1: + count += 1 + n = n >> 1 + i += 1 + return count diff --git "a/\360\237\231\202easy/0231.Power-of-Two/power-of-two.py" "b/\360\237\231\202easy/0231.Power-of-Two/power-of-two.py" new file mode 100644 index 0000000..e5fd0e6 --- /dev/null +++ "b/\360\237\231\202easy/0231.Power-of-Two/power-of-two.py" @@ -0,0 +1,12 @@ +# 231. Power of Two +# https://leetcode.com/problems/power-of-two/ + +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + r, i = 1, 0 + while i <= 32: + if n ^ r == 0: + return True + r = r << 1 + i += 1 + return False diff --git "a/\360\237\231\202easy/1486.XOR-Operation-in-an-Array/xor-operation-in-an-array.py" "b/\360\237\231\202easy/1486.XOR-Operation-in-an-Array/xor-operation-in-an-array.py" new file mode 100644 index 0000000..c4d2b06 --- /dev/null +++ "b/\360\237\231\202easy/1486.XOR-Operation-in-an-Array/xor-operation-in-an-array.py" @@ -0,0 +1,11 @@ +# 1486. XOR Operation in an Array +# https://leetcode.com/problems/xor-operation-in-an-array/description/ + +class Solution: + def xorOperation(self, n: int, start: int) -> int: + r = start + i = 1 + while i < n: + r = r ^ (start + 2 * i) + i += 1 + return r diff --git "a/\360\237\231\202easy/1720.Decode-XORed-Array/decode-xored-array.py" "b/\360\237\231\202easy/1720.Decode-XORed-Array/decode-xored-array.py" new file mode 100644 index 0000000..85e16c3 --- /dev/null +++ "b/\360\237\231\202easy/1720.Decode-XORed-Array/decode-xored-array.py" @@ -0,0 +1,15 @@ +# 1720. Decode XORed Array +# https://leetcode.com/problems/decode-xored-array/description/ + +from typing import List + + +class Solution: + def decode(self, encoded: List[int], first: int) -> List[int]: + # xor 연산은 한번 더 하면 원래 값이 나온다. + result = [first] + i = 1 + for e in encoded: + result.append(result[i - 1] ^ e) + i += 1 + return result From 77ea8aec32f3f75abde4dc887c7237fe188e285e Mon Sep 17 00:00:00 2001 From: iamminji Date: Mon, 8 May 2023 21:02:09 +0900 Subject: [PATCH 23/24] [20230508] Solve BitManipulation easy problems --- .../0342.Power-of-Four/power-of-four.py" | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 "\360\237\231\202easy/0342.Power-of-Four/power-of-four.py" diff --git "a/\360\237\231\202easy/0342.Power-of-Four/power-of-four.py" "b/\360\237\231\202easy/0342.Power-of-Four/power-of-four.py" new file mode 100644 index 0000000..4b60150 --- /dev/null +++ "b/\360\237\231\202easy/0342.Power-of-Four/power-of-four.py" @@ -0,0 +1,10 @@ +# 342. Power of Four +# https://leetcode.com/problems/power-of-four/description/ + +class Solution: + def isPowerOfFour(self, n: int) -> bool: + if n & (n - 1) != 0: + return False + + num = int('10101010101010101010101010101010', 2) + return n & num != n From c03e56fabe4951168e43b92e95ec12abe35100a8 Mon Sep 17 00:00:00 2001 From: iaminji Date: Wed, 3 Apr 2024 23:13:50 +0900 Subject: [PATCH 24/24] [20240403] Solve April challenge --- challenge/2024/04/03_word_search.py | 58 +++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 challenge/2024/04/03_word_search.py diff --git a/challenge/2024/04/03_word_search.py b/challenge/2024/04/03_word_search.py new file mode 100644 index 0000000..5add846 --- /dev/null +++ b/challenge/2024/04/03_word_search.py @@ -0,0 +1,58 @@ +# https://leetcode.com/problems/word-search/?envType=daily-question&envId=2024-04-03 + + +from typing import List + + +class Solution: + + def exist(self, board: List[List[str]], word: str) -> bool: + + for i in range(len(board)): + for j in range(len(board[0])): + if self.check(word, 0, i, j, board): + return True + + return False + + def check(self, word, k, i, j, board): + + if i < 0 or i >= len(board): + return False + + if j < 0 or j >= len(board[0]): + return False + + if k >= len(word): + return False + + if word[k] != board[i][j]: + return False + + # 여기 왔다는 건 단어를 다 찾았다는 의미이다. + if k == len(word) - 1: + return True + + # 이미 확인한 보드를 체크하는 부분 + board[i][j] = '#' + + # 끝까지 하나라도 갔으면 성공한 것이다. + res = ( + self.check(word, k + 1, i + 1, j, board) or + self.check(word, k + 1, i, j + 1, board) or + self.check(word, k + 1, i - 1, j, board) or + self.check(word, k + 1, i, j - 1, board) + ) + # backtracing을 대비에 원복함 + board[i][j] = word[k] + + return res + + +if __name__ == '__main__': + solution = Solution() + + print(solution.exist([["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]], "ABCCED")) + print(solution.exist([["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]], "SEE")) + print(solution.exist([["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]], "ABCB")) + print(solution.exist([["a", "b"], ["c", "d"]], "bacd"))