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

LeetCode 1979: Find Greatest Common Divisor of Array

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

基本資料
#

難易度: easy 第一次嘗試:2025-05-17

  • 提交紀錄:Accepted ×3

解題思路
#

只要最小值和最大值的 GCD。輾轉相除法:gcd(a, b) = gcd(b, a % b),直到 b == 0,答案是 a。

我的解法
#

class Solution:
    def findGCD(self, nums: List[int]) -> int:
        a, b = max(nums), min(nums)
        while b:
            a, b = b, a % b
        return a

第三次提交改成一次掃描同時找最小和最大值,省一次走訪;也可以直接 math.gcd(min(nums), max(nums))。

複雜度
#

時間 O(n + log M),空間 O(1)。

要特別避免的錯誤
#

  • 輾轉相除的迴圈條件是 b != 0,最後回傳 a。

面試口說整理
#

我先找出最小值和最大值,再用輾轉相除法:每次把 (a, b) 換成 (b, a % b),b 變成 0 時 a 就是 GCD。時間 O(n + log M)。

相關文章

LeetCode 952: Largest Component Size by Common Factor
·2 分鐘
LeetCode Hard Math Number-Theory Union-Find Hash-Table Array
LeetCode 952 解題筆記:有共同因數 ⇔ 有共同的質因數;把每個數分解質因數,同一個質因數的 index 用 Union-Find 合併,不用兩兩算 GCD
LeetCode 204: Count Primes
·1 分鐘
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 解題筆記:埃氏篩,只用質數 p 從 p² 開始把倍數劃掉,外層只要到 √n
LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 989: Add to Array-Form of Integer
·1 分鐘
LeetCode Easy Array Math
LeetCode 989 解題筆記:把 k 當成進位,從陣列最後一位往前加,k 還沒用完就繼續往前補位
LeetCode 908: Smallest Range I
·1 分鐘
LeetCode Easy Array Math
LeetCode 908 解題筆記:最大值往下調 k、最小值往上調 k,答案是 max(0, max - min - 2k)
LeetCode 914: X of a Kind in a Deck of Cards
·1 分鐘
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 解題筆記:每種卡片的張數都要能被同一個 X >= 2 整除,也就是所有張數的 GCD >= 2