码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 11. Container With Most Water

时间:2017-03-01 14:28:32      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:color   ack   amp   public   int   div   container   class   理解   

O(n)的做法一开始没想出,看了别人的代码才理解的。

感觉自己又变弱了。。。

 

思路:

首先评估最宽的容器,使用第一行和最后一行。 所有其他可能的容器都不够宽,所以为了容纳更多的水,他们需要更高。 因此,在评估了最宽的容器后,跳过两端的不支持更高高度的线。 然后评估我们到达的新集装箱。 重复,直到没有更多可能的容器。

 

代码如下:

package Num11;

public class Solution {
    public int maxArea(int[] height) {
        int left = 0, right = height.length - 1;
        int maxArea = 0;

        while (left < right) {
            int h = Math.min(height[left], height[right]);
            maxArea = Math.max(maxArea, h * (right - left));
            while (height[left] <= h && left < right) left++;
            while (height[right] <= h && left < right) right--;
        }

        return maxArea;
    }
}

 

LeetCode 11. Container With Most Water

标签:color   ack   amp   public   int   div   container   class   理解   

原文地址:http://www.cnblogs.com/liangyongrui/p/6483818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!