【LeetCode】Container With Most Water

Description

Container With Most Water
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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.

Code

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0, right = height.size() - 1;
        int maxV = 0, vol;
        while (left != right) {
            vol = (right - left) * min(height[right], height[left]);
            maxV = max(maxV, vol);
            if (height[left] < height[right])
                // 左边那条线是短板,如果固定左边的板,让right--,那么新形成的容器一定会容积更小!
                ++left;
            else
                --right;
        }
        return maxV;
    }
};                

Review

这道题中也用了将两个变量分别初始化为区间头尾,根据一定条件将头向后移动,或将尾向前移动的方法。
题中要求的是最大容量,3Sum Closest要求的是最接近的值,或这种情况下可以用这个思路?

这道题中的限制条件是短板长度,既然有一边是短板了,不妨设左边是短板,那么右边再往左边靠近,得到的结果肯定比原来的结果还要小,干脆可以不考虑左边是短板的其他情况了,直接让左边的下一块板子当左板好了。
3Sum Closest中的限制条件是两个数的和。可以根据和target的大小关系来决定如何移动数字才能更靠近target一些。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值