Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
给一串数字,如[1,1],他们的下标索引是0,1,找两个数,使得他们对应的索引下标之差构成容器的底,两个数值对应容器的高。求使得容器面积最大的两个数。
底宽w就是下标索引的差,容器面积取决于高度的较小值。
方法一:暴力求解
class Solution {
public:
int maxArea(vector<int>& height) {
int maxArea=0;
for(int i=0;i<height.size();i++){
for(int j=i+1;j<height.size();j++){
int w = j-i;
int h = min(height[i],height[j]);
maxArea= max(maxArea,w*h);
}
}
return maxArea;
}
};
暴力求解超时了。。。。。
在讨论区发现了很漂亮的解决方法。
class Solution {
public:
int maxArea(vector<int>& height) {
int i=0,j=height.size()-1;
int maxArea = 0;
while(i<j){
int h=min(height[i],height[j]);
int w=j-i;
maxArea = max(maxArea,w*h);
while(height[i]<=h) i++;
while(height[j]<=h) j--;
}
return maxArea;
}
};
还有一种方法:
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right = height.size()-1;
int maxArea = 0;
while(left<right){
maxArea = max(maxArea, min(height[left], height[right])*(right-left));
if(height[left]<height[right]){
left++;
}else{
right--;
}
}
return maxArea;
}
};
就本题而言,每一步的最佳选择必定不是令长的一端向短的一端移动,因为所得矩形的面积只与短边的长度及两端的距离有关,如果我们保留着短边,就只会带来更短的宽度,导致更小的面积。而如果是令短的一端向长的一端移动,决定矩形高度的“短板”就有望获得提升,以抵消宽度减小的副作用,从而有机会使矩形面积增大。如此分析,后者自然是每一步的最佳选择。
后两段代码的方法是一样的,都是使短的一端向长的一端移动,以此来查找最大面积。
参考了下面的文章