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

LeetCode 3507: Minimum Pair Removal to Sort Array I

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

基本資料
#

難易度: easy 第一次嘗試:2025-04-06

  • 提交紀錄:Runtime Error → Accepted

解題思路
#

規則是固定的:每次找「和最小的相鄰 pair」,平手取最左邊,合併成一個數。重複到陣列非遞減為止,回傳操作次數。

n <= 50,每次操作掃一遍是 O(n),最多操作 n 次,直接模擬 O(n^2) 就夠了。

n 到 10^5 的版本(LC 3510)才需要用 heap 加雙向鏈結串列。

我的嘗試:切片賦值給了一個 int
#

nums[min_index:min_index+2] = min_value      # TypeError

切片賦值的右邊必須是 iterable。要把兩個元素換成一個,要寫成 [min_value]。

正確解法
#

class Solution:
    def minimumPairRemoval(self, nums: List[int]) -> int:
        ops = 0
        while any(nums[i] > nums[i + 1] for i in range(len(nums) - 1)):
            best = min(range(len(nums) - 1), key=lambda i: nums[i] + nums[i + 1])
            nums[best:best + 2] = [nums[best] + nums[best + 1]]
            ops += 1
        return ops

min 遇到平手會回傳第一個,剛好符合「取最左邊」。

複雜度
#

時間 O(n^2),空間 O(1)。

要特別避免的錯誤
#

  • 切片賦值右邊放單一值。
  • 平手時取到右邊的 pair:比較時要用 < 而不是 <=。

面試口說整理
#

n 最多 50,所以我直接模擬:只要陣列還不是非遞減,就找和最小的相鄰 pair,平手取最左邊,把它換成兩數的和,計數加一。每次操作 O(n),最多 n 次,總共 O(n^2)。如果 n 很大,就要改用 heap 維護 pair 的和,加上雙向鏈結串列處理合併。

相關文章

LeetCode 1646: Get Maximum in Generated Array
·1 分鐘
LeetCode Easy Array Simulation
LeetCode 1646 解題筆記:照規則生成陣列:偶數位置 nums[i // 2],奇數位置 nums[i // 2] + nums[i // 2 + 1],n = 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 566: Reshape the Matrix
·1 分鐘
LeetCode Easy Array Matrix Simulation
LeetCode 566 解題筆記:元素總數不同就回傳原矩陣;否則第 k 個元素放到 (k // c, k % c)
LeetCode 495: Teemo Attacking
·1 分鐘
LeetCode Easy Array Simulation
LeetCode 495 解題筆記:每次攻擊貢獻 min(到下一次攻擊的間隔, duration),最後一次貢獻完整的 duration
LeetCode 3069: Distribute Elements Into Two Arrays I
·1 分鐘
LeetCode Easy Array Two-Pointers Simulation
LeetCode 3069 解題筆記:照規則模擬:前兩個各放一邊,之後比較兩個陣列的最後一個,放到最後一個比較大的那邊
LeetCode 682: Baseball Game
·1 分鐘
LeetCode Easy Array Stack Simulation
LeetCode 682 解題筆記:用 stack 存有效的分數,C 刪掉最後一個,D 加入兩倍,+ 加入最後兩個的和