leetcode 11. Container With Most Water

33 篇文章 0 订阅
30 篇文章 0 订阅

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.
在这里插入图片描述
Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

tag: array, two pointers

method 1 brute force

暴力解,两层遍历循环. 简单地考虑每个可能的线对的面积,并找出其中的最大面积。

public class Solution {
    public int maxArea(int[] height) {
        int maxarea = 0;
        for (int i = 0; i < height.length; i++)
            for (int j = i + 1; j < height.length; j++)
                maxarea = Math.max(maxarea, Math.min(height[i], height[j]) * (j - i));
        return maxarea;
    }
}

method 2 two pointers

找到最高的线,然后找到左边的最高的线和右边的最高的线,他们之间的面积就是最大的面积。如果有多个相同的最高线,可能要尝试多次

method 3

两根指针法,left和right,每次移动短的那一段,因为如果移动大的,那么在另一端不变的情况下,水量可能会变小,首先宽变小一位,而高度始终是以小的算的。相对来说移动小的,在宽度变小的情况下,更容易获得更大的面积

public int maxArea(int[] height) {
        int left = 0, right = height.length - 1;
        int maxArea = 0;

        while (left < right) {
            maxArea = Math.max(maxArea, Math.min(height[left], height[right])
                    * (right - left));
            if (height[left] < height[right])
                left++;
            else
                right--;
        }

        return maxArea;
    }

summary:

  1. 思考逻辑链:算面积->需要知道长宽-> 宽的话取决于两边短的一边-> 两边-> 两个指针法
  2. 以什么样得标准遍历能得到更大的面积,移动短那一段
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值