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

LeetCode 3618: Split Array by Prime Indices

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

基本資料
#

難易度: medium 第一次嘗試:2025-07-19

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

解題思路
#

index 是質數的放進 A、其他放進 B,回傳 |sum(A) - sum(B)|。

要判斷 0..n-1 每個 index 是不是質數,埃氏篩一次就能全部算好,O(n log log n)。我當時對每個 index 試除到 √i,O(n √n) 也能過,但慢一些(767ms)。

0 和 1 都不是質數。

我的解法
#

from math import isqrt

class Solution:
    def splitArray(self, nums: List[int]) -> int:
        n = len(nums)
        is_prime = [False, False] + [True] * max(0, n - 2)
        for i in range(2, isqrt(n) + 1):
            if is_prime[i]:
                for j in range(i * i, n, i):
                    is_prime[j] = False
        diff = 0
        for i, x in enumerate(nums):
            diff += x if is_prime[i] else -x
        return abs(diff)

n 只有 1 時,is_prime 只會用到前 n 個位置,前面補的 [False, False] 不影響。

複雜度
#

時間 O(n log log n),空間 O(n)。

要特別避免的錯誤
#

  • 判斷的是 index,不是元素的值。
  • 0 和 1 不是質數。

面試口說整理
#

我用埃氏篩一次算出所有 index 是不是質數,再掃一次:質數 index 的加、其他的減,最後取絕對值。時間 O(n log log n),比每個 index 試除快。

相關文章

LeetCode 204: Count Primes
·1 分鐘
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 解題筆記:埃氏篩,只用質數 p 從 p² 開始把倍數劃掉,外層只要到 √n
LeetCode 1979: Find Greatest Common Divisor of Array
·1 分鐘
LeetCode Easy Math Number-Theory Gcd Array
LeetCode 1979 解題筆記:找出最小值和最大值,用輾轉相除法算 GCD
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 1814: Count Nice Pairs in an Array
·1 分鐘
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 解題筆記:把條件移項成 nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]),按這個值分組數 pair,記得取模
LeetCode 313: Super Ugly Number
·1 分鐘
LeetCode Medium Array Math Dynamic-Programming
LeetCode 313 解題筆記:LC 264 的推廣,每個質數一個指針;用 heap 的話要避免同一個數被推進去很多次
LeetCode 396: Rotate Function
·1 分鐘
LeetCode Medium Array Math Dynamic-Programming
LeetCode 396 解題筆記:F(k) 和 F(k - 1) 只差一個公式:F(k) = F(k - 1) + sum - n × 被移到最前面的那個數