iT邦幫忙

1

解LeetCode的學習筆記Day11_Container With Most Water_雙指針

LFI 2025-10-02 12:27:30150 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第十一天

第十一題題目:You are given an integer array height of length n. Find two lines that together with the x-axis form a container, such that the container contains the most water.
給定一個長度為n的整數數組,找到兩條線與X軸形成的容器能裝最多的水

https://ithelp.ithome.com.tw/upload/images/20251002/20179234Mn4WQ7vdZF.png

解題思路

定義雙指針l、r,l從最左邊開始,r從最右邊,算出容器能裝多少水(兩個長度的索引相減*數值小的長度),因為長度高的可以裝較多的水,所以看l、r誰小誰就往下一個索引移動

程式碼如下

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

結語

這題是很簡單的雙指針應用,後續過幾天會有稍微複雜一點的雙指針題目,可以先在簡單題把觀念釐清,了解執行過程與原理


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言