【LeetCode】11. Container With Most Water

Givennnon-negative integersa1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis 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 andnis at least 2.


题意

给定的是垂直于x轴的直线,让你求出两条直线,使得跟x轴围成的面积最小。

所以问题转换为一个矩形一条边取纵坐标小的那根,一条边取横坐标的差值,求这个矩形的面积最大(一开始以为是梯形,明显不合逻辑)。

答案

我自己想了半天的思路是,从前往后遍历,找每个以height[i]为高的矩形的最大值,遍历n次即可。

定义two pointer,一个是m=0,一个是n=size-1,找到第一个比当前 height[i]大的值(++m;--n),此时max(i-m,n-i)*height[i]肯定是以height[i]为高的矩形的最大值。比较n个取最大即为所得。这个时间复杂度还是o(n^2),但是有剪枝,所以通过了。


.但后来翻答案发现还有更简单的思路,就是以底边长遍历,two pointer,一个是m=0,一个是n=size-1,第一次就已经把min(m,n)为边的面积算出来了。然后对m,n小的边进行移动,又算出了以m-1为高的矩形的值

一开始的代码:
class Solution {
public:
    int maxArea(vector<int>& height) {
        int max=0;
        for(int i=0;i<height.size();i++){
            int m=0,n=height.size()-1;
            while(m<i&&height[m]<height[i]) m++;
            while(n>i&&height[n]<height[i]) n--;
            
            int tmp=height[i]*((i-m>n-i)?i-m:n-i);
            if(tmp>max1) max=tmp;
        }
        
        return max;
    }
};

更优秀的代码:
class Solution {
public:
    int maxArea(vector<int>& height) {
        int max=0;
        int m=0,n=height.size()-1;
        while(m<n){
            int tmp=min(height[m],height[n])*(n-m);
            max=tmp>max?tmp:max;
            if(height[m]<height[n]) m++;
            else if(height[m]>height[n])--n;
            else {++m; --n;}
        }
        
        return max;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值