LeetCode 11. Container With Most Water解题报告

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.


分析
画出图像如下
这里写图片描述
大概的意思就是要我们在数轴和两个目标杆之间找到一个最大面积的矩形。

最简单的思路就是找到每个柱子两边的最高柱子然后比较即可,复杂度为O(n^2)。
因为得到一个矩形需要比较2个柱子的高低所以可以考虑使用两个指针对向移动,
从末尾和头分别布置一个指针,每次移动比较矮的柱子,因为高的柱子可能会有其他更高的柱子出现使得面积有扩大的可能,移动2个指针直到相遇,复杂度为O(n)。
AC代码如下:

class Solution {
    public int maxArea(int[] height) {
        int max = 0;
        int left = 1, right = height.length;
        max = (right-left)*(Math.min(height[right-1], height[left-1]));
        while (left < right) {
            if (height[right-1] < height[left-1]) {
                right--;
            } else {
                left++;
            }
            max = max  >= (right-left)*(Math.min(height[right-1], height[left-1])) ? max : (right-left)*(Math.min(height[right-1], height[left-1]));
        }
        return max;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值