首先是 623. Add One Row to Tree (medium)
https://leetcode.com/problems/add-one-row-to-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
class Solution:
def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:
def dfs(root,deep = 1):
if root is None:
return
if deep+1 == depth:
# if root.left:
temp = root.left
valTemp = TreeNode(val)
valTemp.left = temp
root.left = valTemp
# if root.right:
temp = root.right
valTemp = TreeNode(val)
valTemp.right = temp
root.right = valTemp
return
dfs(root.left,deep+1)
dfs(root.right,deep+1)
if depth == 1:
temp = TreeNode(val)
temp.left = root
return temp
dfs(root)
return root
再來是 202. Happy Number (easy)
https://leetcode.com/problems/happy-number
丟一個數字n,把每一位數平方後相加,看最後會不會變成整數1
想法:
原則上就是紀錄的問題,要把跑過的數字記錄下來。
然後就依照題目的要求進行平方相加持續這個過程,若這個過程中有遇到一樣的數字,那就沒救了,return False
class Solution:
def isHappy(self, n: int) -> bool:
path = set()
while n != 1:
temp = str(n)
n = 0
for i in temp:
n += int(i)**2
if n in path:
return False
path.add(n)
return True
#另外一種不用for i in str的寫法
def isHappy(self, n: int) -> bool:
path = set()
while n!=1:
total = 0
while n:
temp = n % 10
n = n // 10
total += temp**2
if total in path:
return False
n = total
path.add(n)
return True
最後是 54. Spiral Matrix (medium)
https://leetcode.com/problems/spiral-matrix/
直接上圖
要用螺旋的方式讀取matrix裡的全部數值,並存到list裡回傳。
想法:
老實說一開始看到這題有被唬到,直接硬肛不太好寫。
後來發現到,其實就是一直旋轉matrix然後把第一列的數字丟到list裡即可
class Solution:
#就是邊丟東西出來邊選轉45度
def spiralOrder(self, matrix):
def turn45(matrix):
if matrix == []:
return []
L,W = len(matrix),len(matrix[0])
result = []
for j in range(-1,-(W+1),-1):
temp = []
for i in range(L):
temp.append(matrix[i][j])
result.append(temp)
return result
ans = []
# print(*turn45(matrix))
while matrix:
temp = matrix.pop(0)
ans += temp
matrix = turn45(matrix)
return ans
# 1 2 3 # 6 9
# 4 5 6 -> # 4 5 6 -> # 5 8 -> # 5 8 -> # 8 7 ->
# 7 8 9 # 7 8 9 # 4 7 # 4 7 # 5 4 # 5 4 -> # 4 5 -> 空
#[1,2,3,6,9,8,7,4,5]
以上為今天的練習,感謝觀看