`
vvaaiinn
  • 浏览: 20934 次
  • 性别: Icon_minigender_1
  • 来自: 大连
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多
题目:

Givennnon-negative integersa1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis 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.

翻译:一个数组的所有数字都是大于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;
    }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics