Skip to content
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
18 changes: 18 additions & 0 deletions insert-interval/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
intervals.append(newInterval)
intervals.sort()
output = [intervals[0]]
for x, y in intervals[1:]:
if output[-1][1] >= x:
output[-1][1] = max(y, output[-1][1])
else:
output.append([x, y])
return output


"""
newInterval을 집어넣은 다음 정렬을 해주면 인덱스 0에 있는 값 기준으로 정렬됨
대소 비교를 해서 이전 배열의 인덱스 1이 현재 배열의 인덱스 0보다 크거나 같으면
값을 변경해주고 아니라면 값을 그냥 추가한다.
"""
25 changes: 25 additions & 0 deletions kth-smallest-element-in-a-bst/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# 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
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
values = []
def dfs(node):
if not node:
return

dfs(node.left)
values.append(node.val)
dfs(node.right)


dfs(root)
return values[k-1]

"""
이진 탐색 트리는 왼쪽은 val보다 작고 오른쪽은 val보다 큼
그렇기에 중위순회 방식으로 하면 자연스럽게 정렬된 상태로 배열에 들어가게 된다.
"""
14 changes: 14 additions & 0 deletions lowest-common-ancestor-of-a-binary-search-tree/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
if root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
return root
7 changes: 7 additions & 0 deletions meeting-rooms/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
for i in range(len(intervals)):
for j in range(i + 1, len(intervals)):
if intervals[i][0] < intervals[j][1] and intervals[j][0] < intervals[i][1]:
return False
return True
13 changes: 13 additions & 0 deletions non-overlapping-intervals/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort()
cnt = 0
pre_end = intervals[0][1]
for i in range(1, len(intervals)):
start, end = intervals[i]
if pre_end > start:
cnt += 1
pre_end = min(end, pre_end)
else:
pre_end = end
return cnt
43 changes: 43 additions & 0 deletions number-of-connected-components-in-an-undirected-graph/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class Solution:
# def countComponents(self, n: int, edges: List[List[int]]) -> int:
# graph = [[] for _ in range(n)]
# for node, adj in edges:
# graph[node].append(adj)
# graph[adj].append(node)

# visited = set()

# def dfs(node):
# visited.add(node)
# for adj in graph[node]:
# if adj not in visited:
# dfs(adj)

# cnt = 0
# for node in range(n):
# if node not in visited:
# cnt += 1
# dfs(node)
# return cnt


def countComponents(self, n: int, edges: List[List[int]]) -> int:
graph = [[] for _ in range(n)]
for node, adj in edges:
graph[node].append(adj)
graph[adj].append(node)

cnt = 0
visited = set()
for node in range(n):
if node in visited:
continue
cnt += 1
queue = deque([node])
while queue:
node = queue.pop()
visited.add(node)
for adj in graph[node]:
if adj not in visited:
queue.append(adj)
return cnt
20 changes: 20 additions & 0 deletions remove-nth-node-from-end-of-list/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
length = 0
node = head
while node:
length += 1
node = node.next

dummy = ListNode(None, head)
node = dummy
for _ in range(length - n):
node = node.next

node.next = node.next.next
return dummy.next
15 changes: 15 additions & 0 deletions same-tree/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# 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
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p and not q:
return True
if not p or not q:
Copy link
Contributor

Choose a reason for hiding this comment

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

2번째 if문과 3번째 if문을 합쳐도 될 거 같아 보이는데, 이렇게는 안 되나요?

if not p or not q or p.val != q.val:
    return False

물론 가독성은 분리했을 때 더 나은 거 같긴 해요.

return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)