LeetCode Everyday:堅持價值投資,做時間的朋友!!!
題目:
給你 n 個非負整數 ,每個數代表座標中的一個點 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 和 。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。
說明:你不能傾斜容器,且 n 的值至少爲 2。
圖中垂直線代表輸入數組 [1,8,6,2,5,4,8,3,7]。在此情況下,容器能夠容納水(表示爲藍色部分)的最大值爲 49。
示例:
示例 1:
輸入:[1,8,6,2,5,4,8,3,7]
輸出:49
代碼
方法一: 雙指針法 題注
執行用時 :72 ms, 在所有 Python3 提交中擊敗了59.70%的用戶
內存消耗 :15.2 MB, 在所有 Python3 提交中擊敗了6.90%的用戶
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i, j, res = 0, len(height) - 1, 0
while i < j:
if height[i] < height[j]:
res = max(res, height[i] * (j - i))
i += 1
else:
res = max(res, height[j] * (j - i))
j -= 1
return res
"""
For Example: input: height = [1,8,6,2,5,4,8,3,7]
output: 49
"""
height = [1,8,6,2,5,4,8,3,7]
solution = Solution()
result = solution.maxArea(height)
print('輸出爲:', result) # 49
參考
- https://leetcode-cn.com/problems/container-with-most-water/solution/container-with-most-water-shuang-zhi-zhen-fa-yi-do/