首页 > 其他 > 详细

LeetCode 11 Container With Most Water 装尽可能多的水

时间:2015-04-22 11:34:29      阅读:217      评论:0      收藏:0      [点我收藏+]
题目:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

翻译:一个数组的所有数字都是大于0的 ,求一对木板的高度,使得装水最多。 容积的短板高度*长度差

解题思路:分别从首尾开始遍历,并用MaxWater标志当前最大装水。如果前面指针指的高度小,则向后。如果后面指的小,则向前。

因为水的最多是短板高度乘以长度差。所以在手首尾指针相遇之前,得到的最大water就是所求。和前面的

代码:

    public int maxArea(int[] height) {
        int left = 0;
        int right = height.length-1;
        int Maxwater = -1;
        while( left < right)
        {
            int water = Math.min(height[left],height[right])*(right - left);
            Maxwater = Math.max(Maxwater,water);
            if(height[left] < height[right])
                left++;
            else 
                right--;
        }
        return Maxwater;
    }

LeetCode 11 Container With Most Water 装尽可能多的水

原文:http://blog.csdn.net/vvaaiinn/article/details/45192523

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!