[LeetCode]Container With Most Water, 解题报告

前言

难怪LeetCode OJ在找工作时被很多人推荐,发现了这道最大蓄水题目就是美团的笔试最后一道题,当时我霸笔只有着一道题目没有答出来,因此也就没有获得面试机会,可惜了

题目

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.


思路

首先,我需要模拟出这个场景,推荐一个画图软件: http://www.processon.com,虽然很小众,但是确实很好用



当从两边向中间考虑时,乘水的面积是由(两端较小的高度)×(两个板之间的宽度)决定的。记录最开始的乘水面积为ans1,然后L向右运动,R向左运动,截止条件是L >= R,并且记录乘水的面积ans,取最大值

以L向左运动为例,当宽度减小时,如果面积变大,必然高度要增加,因此L只需取比前一个L大的值即可,初始L的高度为L1。R向右运动同理


AC代码

public class Solution {
    public int maxArea(int[] height) {
        int i, j, lh, rh, area, tmp, len = height.length;

        lh = height[0];
        rh = height[len - 1];
        area = Math.min(height[0], height[len - 1]) * (len - 1);

        for (i = 1, j = len - 2; i < j;) {
            while (i < j && height[i] <= lh) {
                i++;
            }
            if (i < j) {
                lh = height[i];
            }

            while (j < j && height[j] <= rh) {
                j--;
            }
            if (i < j) {
                rh = height[j];
            }

            tmp = Math.min(lh, rh) * (j - i);

            if (tmp > area) {
                area = tmp;
            }
        }

        return area;
    }
}




原文地址:https://www.cnblogs.com/fuhaots2009/p/3469142.html