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

LeetCode 11: Container With Most Water

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

基本資料
#

難易度: medium 第一次嘗試:2022-10-20

  • 提交紀錄:Runtime Error → Time Limit Exceeded → Accepted ×6 → Wrong Answer ×2 → Accepted

解題思路
#

面積是 寬度 × 兩邊較矮的高度(Two Pointers 模板一)。從兩端開始,寬度最大。每次要移動一邊:

  • 移動比較高的那邊:寬度變小,高度還是被矮的那邊限制,面積不可能變大。
  • 所以移動比較矮的那邊,才有機會找到更高的。

我的嘗試
#

2022 年 11 月重寫時一版把條件寫成 if r > l: l += 1,看的是位置而不是高度,等於每次都移左邊,例如 [3, 5, 1]:答案 3(3 和 5 之間),回傳 2。

正確解法
#

class Solution:
    def maxArea(self, height: List[int]) -> int:
        l, r, best = 0, len(height) - 1, 0
        while l < r:
            best = max(best, (r - l) * min(height[l], height[r]))
            if height[l] < height[r]:
                l += 1
            else:
                r -= 1
        return best

複雜度
#

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

要特別避免的錯誤
#

  • 移動哪一邊要看高度,不是看位置。

面試口說整理
#

我從兩端開始,每次算面積後移動比較矮的那一邊,因為移動高的那邊只會讓寬度變小、高度不會增加。每個位置只看一次,時間 O(n)。

相關文章

LeetCode 15: 3Sum
·2 分鐘
LeetCode Medium Array Two-Pointers Sorting
LeetCode 15 解題筆記:排序後固定第一個數,剩下用對撞指針找兩數和;三個位置都要跳過相同的值,才不會有重複的組合
LeetCode 16: 3Sum Closest
·1 分鐘
LeetCode Medium Array Two-Pointers Sorting
LeetCode 16 解題筆記:排序後固定一個數,對撞指針找另外兩個;比較的是和跟 target 的距離 abs(sum - target)
LeetCode 18: 4Sum
·1 分鐘
LeetCode Medium Array Two-Pointers Sorting
LeetCode 18 解題筆記:排序後兩層迴圈固定前兩個數,剩下用對撞指針;四個位置都要跳過相同的值
LeetCode 455: Assign Cookies
·1 分鐘
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 解題筆記:小孩和餅乾都排序,用最小的、夠大的餅乾滿足最小的小孩;兩個指標各走一次
LeetCode 942: DI String Match
·1 分鐘
LeetCode Easy Array Two-Pointers String Greedy
LeetCode 942 解題筆記:兩個指標分別指向還沒用的最小值和最大值,遇到 I 放最小、遇到 D 放最大
LeetCode 19: Remove Nth Node From End of List
·1 分鐘
LeetCode Medium Linked-List Two-Pointers
LeetCode 19 解題筆記:從 dummy 出發,快指針先走 n + 1 步,再一起走到底,慢指針停在要刪的前一個