【LeetCode 11】盛最多水的容器

题目链接

【题解】


双指针。
一开始l=0,r = len-1
然后不断往中间收缩。
如果发现h[l]<h[r].
如果你让r递减,你会发现只要以h[l]为左端点。(右端(比它大或比他小))肯定没有当前这个情况来的更好了.
所以只能l++了
h[l]>h[r]同理

一开始想到的是一个nlogn的做法。
先从大到小排个序(按照高度)。
然后顺序枚举i
显然1..i这里面的板子组成的矩形的话,一定是以第i个板子的高度为准的(最小).
那么当前的任务就是在里面找一个下标离它最远的板子了。
然后对所有的i取最大值即可。

【代码】

class Solution {
public:
    int maxArea(vector<int>& height) {
         int len = height.size();
         int l = 0,r = len-1;
         int ma = min(height[0],height[r])*r;
         while (l<r){
             if (height[l]<height[r]) l++; 
             else r--;
             ma = max(ma,(r-l)*min(height[l],height[r]));
         }
         return ma;
    }
};

猜你喜欢

转载自www.cnblogs.com/AWCXV/p/11802319.html