给定一个数组height,长度为n,每个数代表坐标轴中的一个点的高度,height[i]是在第i点的高度,请问,从中选2个高度与x轴组成的容器最多能容纳多少水
1.你不能倾斜容器
2.当n小于2时,视为不能形成容器,请返回0
3.数据保证能容纳最多的水不会超过整形范围,即不会超过231-1
数据范围:
如输入的height为[1,7,3,2,4,5,8,2,7],那么如下图:
[1,7,3,2,4,5,8,2,7]
49
[2,2]
2
[5,4,3,2,1,5]
25
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param height int整型一维数组 # @return int整型 # class Solution: def maxArea(self , height: List[int]) -> int: # write code here n=len(height) if n<=1: return 0 i=0 j=n-1 res=0 while i<=j: v=min(height[i],height[j])*(j-i) res=max(res,v) if height[i]< height[j]: i+=1 else: j-=1 return res
贪心算法 + 双指针:每次移动小的那条边来寻求面积最大;木桶的短板原理:用短的木板长度作为高。
时间复杂度:O(n) 空间复杂度:O(1)
class Solution:
def maxArea(self , height: List[int]) -> int:
res = 0
low = 0
high = len(height) - 1
while low < high:
temp = low if height[low] < height[high] else high
res = max(res, (high-low)*height[temp])
if temp == low:
low += 1
else:
high -= 1
return res
class Solution: def maxArea(self , height: List[int]) -> int: # write code here if len(height) < 2: return 0 left = 0;right = len(height)-1 area = (right-left)*min(height[left], height[right]) while left < right: area = max(area, (right-left)*min(height[left], height[right])) if height[left]<= height[right]: left += 1 else: right -= 1 return area
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param height int整型一维数组 # @return int整型 # class Solution: def maxArea(self , height: List[int]) -> int: # write code here n=len(height) if n<2: return 0 left=0 right=n-1 res=0 while left <right: area=min(height[left],height[right])*(right-left); res=max(res,area) if height[left]<height[right]: left+=1 else: right-=1 return res