【LeetCode】11. Container With Most Water

来源:互联网 发布:蒙文软件免费下载 编辑:程序博客网 时间:2024/06/06 18:57

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;    }};


0 0