[C++]LeetCode 11: Container With Most Water(最大容积/最大矩形面积)

16 篇文章 0 订阅
16 篇文章 1 订阅

Problem:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.


分析:

题目即为求(i, ai),(i, 0),(j, aj),(j, 0)组成的图形的最大矩形面积面积(以ai和aj中小者为矩形的高)。

利用二分法,冲首位两边缩进,每次求得面积与最大面积比较并更新,

同时对ai,aj中小者的位置进行更新(大者可能会成为下一次的高以更新面积;而小者不变只能得到小于等于小者的高,且宽度在减小无法更新面积)。


AC Code(C++):

class Solution {
public:
    //45 / 45 test cases passed.
    //Runtime: 29 ms
    
    int maxArea(vector<int>& height) {
        //排除无效情况
        if (height.size() < 2) {
            return 0;
        }
        
        int begin = 0;
        int end = (int)height.size() - 1;
        int container = 0;
        while (begin < end) {
            int size = min(height[begin], height[end])*(end - begin);
            if (size > container) {
                container = size;
            }
            if (height[begin] < height[end]) {
                ++begin;
            }
            else{
                --end;
            }
        }
        return container;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值