题解 | #盛水最多的容器#
盛水最多的容器
https://www.nowcoder.com/practice/3d8d6a8e516e4633a2244d2934e5aa47
class Solution:
def maxArea(self , height: List[int]) -> int:
# write code here
if len(height) < 2:
return 0
left = 0
right = len(height) - 1
res = 0
while left < right:
water = (right-left)*min(height[left], height[right])
res = max(res, water)
if height[left] < height[right]: # 贪心思想
left += 1
else:
right -= 1
return res
解题思路
使用双指针和贪心思想。
- 双指针分别指向两端,向中间靠拢;
- 计算当前容器容量值,取历史最大值;
- 利用贪心思想决定下标的变化,由于较长的一边比较短的一边更可能出现更大容积,因此当左指针对应的元素小于右指针对应的元素的时候,左指针加一;否则右指针减一。
复杂度
时间复杂度为O(N),空间复杂度为O(1)。


查看11道真题和解析