Leetcode 11. Container With Most Water

https://leetcode.com/problems/container-with-most-water/

class Solution {
public:
    int maxArea(vector<int>& height) {
        /*
        逼近法
        两端进行逼近
        每次舍弃短边,因为不存在短边为边的另一个矩形比当前矩形要大【宽变小,高最多为短边】
        */
        #include<algorithm>
        using namespace std;
        int ans=0;
        int l=0,r=height.size()-1;
        while(l<r){
            ans=max(ans,min(height[l],height[r])*(r-l));
            if(height[l]<height[r]) ++l;
            else --r;
        }
        return ans;
    }
};

python版本

class Solution:
    def maxArea(self, height: List[int]) -> int:
        l,r=0,len(height)-1
        ans=0
        while l<r:
            ans=max(ans,min(height[l],height[r])*(r-l))
            if height[l]>height[r]:
                r-=1
            else:
                l+=1
        return ans
posted @ 2019-04-26 13:16  benda  阅读(87)  评论(0编辑  收藏  举报