美文网首页
11. Container With Most Water

11. Container With Most Water

作者: 衣介书生 | 来源:发表于2018-04-16 21:33 被阅读13次

题目分析

暴力实现即可,注意短板效应,还有何时移动边界。

代码

class Solution {
    public int maxArea(int[] height) {
        int ans = 0;
        int l = 0, r = height.length - 1;
        while(l < r) {
            // 注意短板效应,所以要取左右高度的最小值
            ans = Math.max(ans, Math.min(height[l], height[r]) * (r - l));
            // 如果是左边的更矮,那么往右移动左边界(看看右边有没有更高的)
            if(height[l] < height[r]) {
                l ++;
            } else {
                r --;
            }
        }
        return ans;
    }
}

相关文章

网友评论

      本文标题:11. Container With Most Water

      本文链接:https://www.haomeiwen.com/subject/gckykftx.html