LeetCode 11. 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.
  • 地址

题目分析

  • 容器蓄水问题:双指针对撞解法
  • 用两个指针 left 与 right 分别用来指示容器的左边界和右边界。初始化 left 在 0 索引处,right 在 height.length - 1 索引处。比较 height[left] 与 height[right] 的大小,假设 height[right]大,那么根据短板原理, 说明 [left ~ right] 形成的容器的蓄水面积受到 height[left]的限制。并且以left作为左边界,left + 1, left + 2….right-1作为右边界的容器蓄水面积都不如 [left ~ right]大,因为要么相等高度 height[left] 下,宽度不及 [left ~ right] ,要么甚至高度都不及 height[left] 。 所以此刻更新蓄水最大面积,然后动短板,让 left++,才有可能新形成的容器面积最大。
    当然,如果 height[left]大,也是相同道理,动right指针,right–。
    持续以上过程,直至 两指针相遇,无法形成容器。

经验教训

  • 双指针对撞解法解决容器蓄水问题

代码实现

class Solution {
    public int maxArea(int[] height) {
        if (height == null || height.length == 1) {
            return 0;
        }
        int left = 0;
        int right = height.length - 1;
        int maxArea = Integer.MIN_VALUE;
        int curArea = 0;
        while (left < right) {
            if (height[left] < height[right]) {
                curArea = height[left] * (right - left);
                ++left;
            }else {
                curArea = height[right] * (right - left);
                --right;
            }
            maxArea = maxArea > curArea ? maxArea : curArea;
        }
        return maxArea;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值