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

LeetCode 1791: Find Center of Star Graph

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

基本資料
#

難易度: easy 第一次嘗試:2022-11-22

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

解題思路
#

星狀圖的中心連到其他每個點,所以每一條邊都包含中心。前兩條邊共同的那個端點就是中心,O(1),不用建圖或數 degree(BFS 一篇的圖論基礎)。

我的解法
#

class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        a, b = edges[0]
        return a if a in edges[1] else b

複雜度
#

時間 O(1),空間 O(1)。

要特別避免的錯誤
#

  • 數 degree 也可以,但只需要兩條邊。

面試口說整理
#

中心點出現在每一條邊上,所以我只看前兩條邊,共同的那個端點就是答案。時間 O(1)。

相關文章

LeetCode 997: Find the Town Judge
·1 分鐘
LeetCode Easy Array Hash-Table Graph
LeetCode 997 解題筆記:法官被其他 n - 1 個人信任而且不信任任何人,所以 in-degree - out-degree == n - 1
LeetCode 1337: The K Weakest Rows in a Matrix
·1 分鐘
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
LeetCode 1337 解題筆記:每列的士兵都在前面,用二分找第一個 0 就是士兵數;照(士兵數, 列號)排序取前 k 個
LeetCode 2331: Evaluate Boolean Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 2331 解題筆記:葉子是 0 或 1,內部節點 2 是 OR、3 是 AND,後序遞迴計算
LeetCode 1379: Find a Corresponding Node of a Binary Tree in a Clone of That Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1379 解題筆記:兩棵樹同時走,原樹走到 target 時,複製樹上的同一個位置就是答案;比的是節點本身
LeetCode 1108: Defanging an IP Address
·1 分鐘
LeetCode Easy String
LeetCode 1108 解題筆記:把每個 . 換成 [.]
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 解題筆記:每個單字的字元次數都不超過 chars 的次數才算能組成,加總這些單字的長度