LeetCode OJ-11.Container With Most Water

LeetCode OJ-11.Container With Most Water

题目描述

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 and n is at least 2.

题目理解

​ 装的水的量,定义为两条直线中较短的一直线的长度与两直线纵坐标的差值的乘积。若不考虑超时,可以用最直接的方法,最外层循环迭代第1条直线的位置,内层循环迭代第2条直线的位置,依次求面积。但这样是AC不了的,所以就要考虑其他办法了。

​ 先看装水量的计算,装水量仅与两直线中较短的一条与横坐标差值有关,也就是说,要使装水量更大,可以选择提升短板,或者增大两直线横坐标差值,因为有两个未知量没有别的条件,处理不了,所以我们需要限定其中一个条件,这里我们使用两个迭代器,分别指向i=0与j=vec.size() - 1,如此,在移动迭代器时,横坐标差值是在减小的,只要短板被提升,装水量就有可能被提升,但如果提升较长的直线,对装水量是不会有任何提升的。在两迭代器向中心移动的过程中,及时更新max_area即可。具体代码如下:

Code

#define MAX(m, n) ( (m > n) ? m : n )
#define MIN(m, n) ( (m < n) ? m : n )

class Solution {
public:
    int maxArea(vector<int>& height) {
        int max = 0;
        int sz = (int) height.size();
        int i = 0;
        int j = sz - 1;
        while (i < j) {
            max = MAX(max, (MIN(height[i], height[j]) * (j - i)));
            if (height[i] < height[j]) {
                ++i;
            }
            else {
                --j;
            }
        }
        return max;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值