leetcode-5.13[867. 轉置矩陣、669. 修剪二叉搜索樹、1029. 兩地調度](python實現)

題目1

在這裏插入圖片描述

題解1

class Solution:
    def transpose(self, A: List[List[int]]) -> List[List[int]]:
        n = len(A[0])
        m = len(A)
        B = [[None for _ in range(len(A))]for _ in range(len(A[0]))]
        print(B)
        for i in range(m):
            for j in range(n):
                B[j][i] = A[i][j] 
        return B

附上題目鏈接

題目2

在這裏插入圖片描述

題解2

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:
        """
            利用搜索二叉樹的特定(左子樹節點值 < 根節點值 < 右子樹節點值)
        """

        # root爲空返回空
        if root is None:
            return root
        # root的值小於L值,只考慮它的右節點
        if root.val < L:
            return self.trimBST(root.right, L, R)
        # root的值大於L值,只考慮它的左節點
        if root.val > R:
            return self.trimBST(root.left, L, R)
        # 更新左右節點(去除不滿足條件的)
        root.right = self.trimBST(root.right, L, R)
        root.left = self.trimBST(root.left, L, R)
        return root

附上題目鏈接

題目3

在這裏插入圖片描述

題解3

class Solution:
    def twoCitySchedCost(self, costs: List[List[int]]) -> int:
        # 貪心算法
        """
            公司首先將這 2N個人全都安排飛往 BB 市,再選出 NN 個人改變它們的行程,讓他們飛往 AA                 市。如果                 選擇改變一個人的行程,那麼公司將會額外付出 price_A - price_B 的費用,這個費用可正可負。
        """
        costs.sort(key = lambda x : x[0] - x[1]) # 根據price_A - price_B的值排序,取出前半部分去A市,後半部分去B市
        n = len(costs)//2
        total = 0
        for i in range(n):
            total += costs[i][0] + costs[n+i][1]
        return total

附上題目鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章