↓快轉到主要內容
  1. LeetCode/

LeetCode 3898: Find the Degree of Each Vertex

·1 分鐘· ·
LeetCode Easy Graph Matrix Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2026-04-12

  • 提交紀錄:Accepted(一次通過)

解題思路
#

鄰接矩陣裡 matrix[i][j] = 1 代表 i 和 j 之間有邊,所以頂點 i 的度數就是第 i 列的總和。無向圖的矩陣是對稱的,我當時加的是每一欄,結果一樣。

我的解法
#

class Solution:
    def findDegrees(self, matrix: List[List[int]]) -> List[int]:
        return [sum(row) for row in matrix]

複雜度
#

時間 O(n²),空間 O(n)(輸出)。

要特別避免的錯誤
#

  • 如果是有向圖,列的總和是出度、欄的總和是入度,就不能混用。

面試口說整理
#

鄰接矩陣的第 i 列記錄 i 跟誰相連,所以把每一列加總就是度數。時間 O(n²)。

相關文章

LeetCode 997: Find the Town Judge
·1 分鐘
LeetCode Easy Array Hash-Table Graph
LeetCode 997 解題筆記:法官被其他 n - 1 個人信任而且不信任任何人,所以 in-degree - out-degree == n - 1
LeetCode 892: Surface Area of 3D Shapes
·1 分鐘
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 解題筆記:每疊 v 個方塊有 4v + 2 個面,再扣掉跟上方和左方相鄰的疊重疊的 2 × min 面
LeetCode 883: Projection Area of 3D Shapes
·1 分鐘
LeetCode Easy Array Math Geometry Matrix
LeetCode 883 解題筆記:俯視是非 0 的格子數,正視和側視分別是每一列、每一欄的最大值總和
LeetCode 867: Transpose Matrix
·1 分鐘
LeetCode Easy Array Matrix Simulation
LeetCode 867 解題筆記:轉置後的大小是 n × m,res[j][i] = matrix[i][j];Python 可以用 zip(*matrix)
LeetCode 832: Flipping an Image
·1 分鐘
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 解題筆記:每一列先左右反轉再把 0、1 互換;可以用左右指針同時做
LeetCode 766: Toeplitz Matrix
·1 分鐘
LeetCode Easy Array Matrix
LeetCode 766 解題筆記:同一條對角線的元素都相同,等價於每一格都等於左上角那格