11. 盛最多水的容器
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
示例:
输入:
1,8,6,2,5,4,8,3,7
输出:
49
水题 1遍暴力-时间超限
卡在了最后一组超多数据的测试用例上
很明显非暴力解决
class Solution {
public:
int maxArea(vector<int>& height) {
//time limit exceeded
int n = height.size();
vector <int> buck(n);
for(int i=0;i<n;i++)
{
int max=0;
for(int j=i+1;j<n;j++)
{
int temp=min(height[i],height[j])*(j-i);
if(temp>max)
max=temp;
}
buck[i]=max;
}
int max=0;
for(int i=0;i<n;i++)
{
if(buck[i]>max)
max=buck[i];
}
return max;
}
};
二次优化 前后指针搜索
解题关键:
移动高的桶边并不可能获得更好的情况,因此移动矮的桶边
class Solution {
public:
int maxArea(vector<int>& height) {
//accept
int n = height.size();
int buck=0;
int left=0,right=n-1;
while(left<right)
{
buck=max(buck,(right-left)*min(height[right],height[left]));
if(height[right]<height[left])
right--;
else left++;
}
return buck;
}
};