今天继续刷LeetCode,第11题,求最大的储水量。
分析:
方法一:简单粗暴,通过两层循环,找到两根柱子之间的最小值,然后求面积,并输出面积的最大值;
方法二:双指针法,减少比较次数,通过一次遍历找到面积的最大值。
问题:
附上C++代码1:
class Solution {
public:
int maxArea(vector<int>& height) {
int max_contain=0;
int min_len,s;
for(int i=0;i<height.size();i++)
for(int j=i+1;j<height.size();j++)
{
min_len=min(height[i],height[j]);
s=min_len*(j-i);
max_contain=max(max_contain,s);
}
return max_contain;
}
};
附上C++代码2:
class Solution {
public:
int maxArea(vector<int>& height) {
int max_contain=0;
int left=0,right=height.size()-1;
while(left<right)
{
max_contain=max(max_contain,min(height[left],height[right])*(right-left));
if(height[right]>height[left])
left++;
else
right--;
}
return max_contain;
}
};
附上Python代码:
class Solution:
def maxArea(self, height: List[int]) -> int:
l=0
r=len(height)-1
max_area=0
while l<r:
max_area=max(max_area,(r-l)*min(height[r],height[l]))
if height[r]>height[l]:
l+=1
else:
r-=1
return max_area