題目
原題頁面:https://leetcode.com/problems/container-with-most-water/
題目型別:Array, Two Pointers
難度評價:Medium
類似題目:(H) Trapping Rain Water
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
分析
貪婪法的思想,用兩個指標從陣列的左邊和右邊開始,向中間搜尋。依據的理由有兩點:
1、因為一開始底邊長就已經是最大,兩個指標向中間移動的時候,底邊長只會變短,因此如果此時面積要變大的話,只能是兩條高中的最短者比移動前的最短高更高,否則就無需考察,直接continue到下一次的迴圈。
2、因此,每次選擇移動左指標還是右指標,優先選擇當前高度最短的那個,以期尋找到更高的邊。如果此時選擇移動當前高度最高的那個,就有可能跳過了最優解。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-container-with-most-water/
