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

LeetCode 2105: Watering Plants II

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

基本資料
#

難易度: medium 第一次嘗試:2026-01-24

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

解題思路
#

兩個人同時開始、每株花的時間一樣,所以第 t 步 Alice 在 t、Bob 在 n - 1 - t,就是對撞指針。

每一步:

  • 水夠就直接澆,不夠就先補滿(次數 +1)再澆。
  • left == right(奇數長度的中間那株):由水比較多的人澆,一樣多由 Alice 澆。只要「比較多的那個」水夠,就不用補水;否則補一次。

我的解法
#

class Solution:
    def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
        a, b = capacityA, capacityB
        left, right = 0, len(plants) - 1
        refills = 0
        while left < right:
            if a < plants[left]:
                a = capacityA
                refills += 1
            a -= plants[left]
            if b < plants[right]:
                b = capacityB
                refills += 1
            b -= plants[right]
            left += 1
            right -= 1
        if left == right and max(a, b) < plants[left]:
            refills += 1                       # 中間那株:水多的人也不夠才補
        return refills

複雜度
#

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

要特別避免的錯誤
#

  • 補水時寫成 a = capacityA 之後忘了扣掉這株的水量。
  • 中間那株讓兩個人都澆,或固定讓 Alice 澆。

面試口說整理
#

兩個人速度一樣,所以 Alice 從左、Bob 從右就是對撞指針。每一步水不夠就先補滿再澆,補水次數加一。奇數長度時兩人會在中間相遇,由水多的人澆,只有水多的人也不夠時才補一次。時間 O(n)。

相關文章

LeetCode 1877: Minimize Maximum Pair Sum in Array
·1 分鐘
LeetCode Medium Two-Pointers Greedy Sorting Array
LeetCode 1877 解題筆記:排序後最小配最大、次小配次大,對撞指針取配對和的最大值
LeetCode 3775: Reverse Words With Same Vowel Count
·1 分鐘
LeetCode Medium String Simulation Two-Pointers
LeetCode 3775 解題筆記:先數第一個字的母音數,後面母音數一樣的字就反轉
LeetCode 1498: Number of Subsequences That Satisfy the Given Sum Condition
·2 分鐘
LeetCode Medium Two-Pointers Sorting Binary-Search Array
LeetCode 1498 解題筆記:子序列只看最小值和最大值,排序後順序無關;固定最小值 nums[left],中間的元素任意選,共 2^(right - left) 種
LeetCode 923: 3Sum With Multiplicity
·3 分鐘
LeetCode Medium Two-Pointers Sorting Hash-Table Counting Array
LeetCode 923 解題筆記:排序後固定第一個數、對撞指針找另外兩個;兩端值相同時用組合數一次算完,不同時把兩端各自的重複數相乘
LeetCode 948: Bag of Tokens
·1 分鐘
LeetCode Medium Two-Pointers Greedy Sorting Array
LeetCode 948 解題筆記:排序後,用最小的 token 換分數、用最大的 token 換能量;只有分數 > 0 才能換能量,換不了就停
LeetCode 825: Friends Of Appropriate Ages
·2 分鐘
LeetCode Medium Two-Pointers Sorting Binary-Search Array
LeetCode 825 解題筆記:排序後,每個人能送出邀請的對象是年齡落在 (0.5 × age + 7, age] 的一段區間,用兩個同向指針維護區間再扣掉自己