[LeetCode]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.

在二维坐标系里,有一组长短不一垂直线段,用(iai)来表示每一条线,用任意两条线段和 x 轴可以组成一个容器,求容量最大的容器的容积。

简单的做法是采用二重循环遍历所有组合保利求解,找出最大的容器,但是这样做会导致超时。

更为合理的解法是,用两个指针分别指向数组的两端,当左边指针指向的数大于右边时,右边指针左移;当右边大于左边时,左边指针右移。重复此操作指导左边指针与右边指针会和。在遍历的过程中保存每次的容器容积,最后返回最大值即可。


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值