11. Container With Most Water

刷题笔记

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 the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.

Notice that you may not slant the container.
在这里插入图片描述

思路

  1. 最容易想到的思路,还是类似于对数组进行一个两层循环的遍历,这样选出容量的最大值,在正确性上是正确的,但是时间耗费太多。
  2. 换一种一遍两头遍历的思路,即从两侧开始往中间遍历,每次移动的那个选项是二者中比较小的那个。这里移动的目的是为了把这个短板替换掉,因为两个高度中的短板是限制面积的主要因素。
  3. 所以移动的原则是要找到一个比开始移动的位置的数值大的数。
  4. 这样移动到最后,遍历所有情况后,自然可以判断留下最大的容量。

代码实现

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值