Skip to content

[saysimple] 2주차 문제 풀이입니다. #66

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

Merged
merged 3 commits into from
May 12, 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
20 changes: 20 additions & 0 deletions invert-binary-tree/saysimple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 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
# TC, SC: O(n), O(n)
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None

left = root.left
root.left = root.right
root.right = left

self.invertTree(root.left)
self.invertTree(root.right)

return root
20 changes: 20 additions & 0 deletions linked-list-cycle/saysimple.py
Copy link
Contributor

Choose a reason for hiding this comment

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

pos를 실제로 추가하셔서 풀이를 하셨네요! 몇 가지 궁금한게 있습니다.

  • 첫번째 if-statement 이 베이스 케이스를 필터하는거라면 리턴벨류를 boolean으로 하는게 더 맞지 않을까 생각해봅니다!
  • SC 부분에 대한 의문이 있습니다. pos 파라미터를 따로 지정해주셨기 때문에 각 노드에 pos가 추가되면 O(n)이 되는게 아닌가 생각합니다..!

Copy link
Author

@say828 say828 May 12, 2024

Choose a reason for hiding this comment

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

  1. 맞습니다. Return False를 해주는 것이 타입에 맞습니다. 저렇게 작성한 이유는 제 경험에 한해서지만 현업 기준으로 객체가 없다는 False보단 None으로 처리하는 경우가 많고(객체가 할당되지 않았다=None이다, 파이썬 index같은 함수들에서 False가 아닌 -1이나 None을 리턴하는 이유) 파이썬의 if문에서 None은 False에 포함되기 때문에 사용하였습니다. 감사합니다!

  2. O(n)이 시간복잡도 기준이라면 O(n)이 맞습니다. 공간 복잡도라면 해당 문제에서 원래 주어졌던 O(1)개의 객체에 변수가 추가된 것이기 때문에 O(1 + 1) = O(1) 이어서 O(1)이라 작성하였습니다. O(n)으로 보이신다면 원래 O(n)인 것을 제가 O(1)로 잘못 작성한게 아닐까 싶어요.

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# TC, SC: O(n), O(1)
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head:
return None

head.pos = 0

while head.next:
if hasattr(head.next, "pos"):
return True
head.next.pos = head.pos + 1
head = head.next

return False
55 changes: 55 additions & 0 deletions merge-two-sorted-lists/saysimple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# TC, SC: O(n), O(n)
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not (list1 and list2):
return list1 if list1 else list2

ret = ListNode(0, None)
head = ret

while list1 and list2:
a, b = list1.val, list2.val
print(a, b)

if a < b:
print(1)
next = ListNode(a, None)
ret.next = next
ret = next
list1 = list1.next
elif a > b:
print(2)
next = ListNode(b, None)
ret.next = next
ret = next
list2 = list2.next
else:
for i in range(2):
next = ListNode(a, None)
ret.next = next
ret = next
list1, list2 = list1.next, list2.next
print(head)

if list1:
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
Author

Choose a reason for hiding this comment

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

그게 훨씬 좋아 보여요. 감사합니다!

while list1:
next = ListNode(list1.val, None)
ret.next = next
ret = next
list1 = list1.next

if list2:
while list2:
next = ListNode(list2.val, None)
ret.next = next
ret = next
list2 = list2.next

head = head.next

return head
27 changes: 27 additions & 0 deletions reverse-linked-list/saysimple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# TC, SC: O(n), O(1)
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None

if not head.next:
return head

prev_node = head
node = prev_node.next
prev_node.next = None

while node.next:
next_node = node.next
node.next = prev_node
prev_node = node
node = next_node

node.next = prev_node

return node
24 changes: 24 additions & 0 deletions valid-parentheses/saysimple.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# TC, SC: O(n), O(n)
class Solution:
def isValid(self, s: str) -> bool:
arr = []

for c in s:
if c in ["(", "[", "{"]:
arr.append(c)
continue
else:
if not arr:
return False
b = arr.pop()
if b == "(" and c == ")":
continue
if b == "[" and c == "]":
continue
if b == "{" and c == "}":
continue
return False
if arr:
return False
else:
return True