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

来源:互联网 发布:花生壳linux 编辑:程序博客网 时间:2024/05/20 09:08

装最多水的容器

  1. 题目

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

    注意事项
    容器不可倾斜。

  2. 样例

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

  3. 题解

首先理解题意,两条垂直线和X轴组成的容器的储水面积S=Math.min(heights[left],heights[right])*(right-left)。可以通过首尾双指针相向遍历,每次移动值较小的那个指针,直至两指针相遇。

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.9.23

0 0
原创粉丝点击