题目
给你 n 个非负整数 a,a…,a每个数代表坐标中的一个点 (i, a) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, a) 和 (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
方案一(暴力解法)
class Solution:
def maxArea(self, height: List[int]) -> int:
res = 0
for i in range(len(height)):
for j in range(i + 1, len(height)):
res = max(res, (j - i) * min(height[i], height[j]))
return res
class Solution:
def maxArea(self, height: List[int]) -> int:
# dp[i] 表示 前 i 个柱子中能容纳水的最大数量
dp = [0] * len(height)
for i in range(1, len(height)):
for j in range(i): # 遍历之前每一个柱子,找到容纳水的最大值
dp[i] = max(dp[i], dp[i - 1], (i - j) * min(height[i], height[j]))
return dp[-1]
class Solution:
def maxArea(self, height: List[int]) -> int:
i, j = 0, len(height) - 1
res = 0
while i < j:
res = max(res, (j - i) * min(height[i], height[j]))
# 等于的时候移动哪一个都可以
if height[i] < height[j]:
i += 1
else:
j -= 1
return res
- 时间复杂度
- 双指针用法总体来说有两种
- 快慢指针:指针在同一端,根据不同的条件往前步进;同时两个指针之间也形成了窗口(window)
- 两个指针分别位于两端,往中间靠拢
- 此处将指针放在两端,每次移动较低的指针(因为移动高的指针会因为更低的指针导致面积必然减小)
原文
https://leetcode-cn.com/explore/interview/card/2020-top-interview-questions/280/array/1247/
https://leetcode-cn.com/problems/container-with-most-water/solution/sheng-zui-duo-shui-de-rong-qi-by-leetcode/