【LeetCode 中等題】6-盛最多水的容器
宣告:
今天是中等題第6道題。給定 n 個非負整數 a1,a2,...,an,每個數代表座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別為 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。以下所有程式碼經過樓主驗證都能在LeetCode上執行成功,程式碼也是借鑑別人的,在文末會附上參考的部落格連結,如果侵犯了博主的相關權益,請聯絡我刪除
(手動比心ღ( ´・ᴗ・` ))
正文
題目:給定 n 個非負整數 a1,a2,...,an,每個數代表座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別為 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。
說明:你不能傾斜容器,且 n 的值至少為 2。
圖中垂直線代表輸入陣列 [1,8,6,2,5,4,8,3,7]。在此情況下,容器能夠容納水(表示為藍色部分)的最大值為 49。
示例:
輸入: [1,8,6,2,5,4,8,3,7] 輸出: 49
解法1。最常規就是用2個for迴圈遍歷所有組合並更新最大面積,但會超時,所以嘗試用雙指標法,左右各一個,向中間靠攏,移動條件是比較左右的元素大小,小的那個移動,程式碼如下。(這種方法是什麼原理肯定可以收斂到最大值的證明有相關討論,可以看這裡https://leetcode.com/problems/container-with-most-water/discuss/6089/anyone-who-has-a-on-algorithm)
執行用時: 132 ms, 在Container With Most Water的Python3提交中擊敗了12.97% 的使用者
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
l = 0
r = len(height)-1
max_area = 0
while l < r:
max_area = max(max_area, min(height[l],height[r])*(r-l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return max_area
解法2。解法1的改良版本,就是l、r的更新更快了,用while更新使之找到一個比當前最低高度更高的值,程式碼如下。
執行用時: 72 ms, 在Container With Most Water的Python3提交中擊敗了93.93% 的使用者
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
l = 0
r = len(height) - 1
max_area = 0
while l < r:
width = min(height[l], height[r])
max_area = max(max_area, width*(r-l))
while height[l] <= width and l < r: l += 1 # 注意這裡一定是 <=,不然就可能不會進這2個while迴圈更新l、r了
while height[r] <= width and l < r: r -= 1
return max_area
結尾
解法1:官方解法
解法2:LeetCode