383.Container With Most Water-装最多水的容器(中等题)

来源:互联网 发布:手机淘宝购物要需要哪 编辑:程序博客网 时间:2024/05/20 07:17

装最多水的容器

  1. 题目

    给定 n 个非负整数 a1, a2, …, an, 每个数代表了坐标中的一个点 (i, ai)。画 n 条垂直线,使得 i 垂直线的两个端点分别为(i, ai)和(i, 0)。找到两条线,使得其与 x 轴共同构成一个容器,以容纳最多水。

    注意事项
    容器不可倾斜。

  2. 样例

    给出[1,3,2], 最大的储水面积是2.

  3. 题解

    参看363.Trapping Rain Water-接雨水(中等题)

public class Solution {    /**     * @param heights: an array of integers     * @return: an integer     */    public int maxArea(int[] heights) {        int max = 0;        int left = 0;        int right = heights.length-1;        while (left < right)        {            max = Math.max(max,Math.min(heights[left],heights[right])*(right-left));            if (heights[left] < heights[right])            {                left++;            }            else            {                right--;            }        }        return max;    }}

Last Update 2016.11.13

0 0