Skip to content

Commit 4bdfd65

Browse files
Merge pull request #1584 from printjin-gmailcom/main
[printjin-gmailcom] week 12 solutions
2 parents f552959 + 13f26f2 commit 4bdfd65

File tree

5 files changed

+77
-0
lines changed

5 files changed

+77
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from typing import List
2+
3+
class Solution:
4+
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
5+
intervals.sort(key=lambda x: x[1])
6+
count = 0
7+
end = float('-inf')
8+
for start, finish in intervals:
9+
if start < end:
10+
count += 1
11+
else:
12+
end = finish
13+
return count
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import (
2+
List,
3+
)
4+
5+
class Solution:
6+
def count_components(self, n: int, edges: List[List[int]]) -> int:
7+
parent = [i for i in range(n)]
8+
def find(x):
9+
if parent[x] != x:
10+
parent[x] = find(parent[x])
11+
return parent[x]
12+
for a, b in edges:
13+
root_a = find(a)
14+
root_b = find(b)
15+
if root_a != root_b:
16+
parent[root_a] = root_b
17+
n -= 1
18+
return n
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def removeNthFromEnd(self, head, n):
3+
dummy = ListNode(0, head)
4+
fast = slow = dummy
5+
for _ in range(n):
6+
fast = fast.next
7+
while fast.next:
8+
fast = fast.next
9+
slow = slow.next
10+
slow.next = slow.next.next
11+
return dummy.next

same-tree/printjin-gmailcom.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Solution:
2+
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
3+
if not p and not q:
4+
return True
5+
if not p or not q:
6+
return False
7+
if p.val != q.val:
8+
return False
9+
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Codec:
2+
def serialize(self, root):
3+
def dfs(node):
4+
if not node:
5+
vals.append("None")
6+
return
7+
vals.append(str(node.val))
8+
dfs(node.left)
9+
dfs(node.right)
10+
11+
vals = []
12+
dfs(root)
13+
return ",".join(vals)
14+
15+
def deserialize(self, data):
16+
def dfs():
17+
val = next(vals)
18+
if val == "None":
19+
return None
20+
node = TreeNode(int(val))
21+
node.left = dfs()
22+
node.right = dfs()
23+
return node
24+
25+
vals = iter(data.split(","))
26+
return dfs()

0 commit comments

Comments
 (0)