LeetCode 11. Container With Most

2016-12-01  本文已影响35人  stevewang

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

大致意思就是给定一组数,从中选择两个数作为高与X轴形成矩形,求最大的矩形面积
求解思路很简单,矩形的面积由宽度和高度共同决定,其中宽度就是两个数下标的距离,而高度主要取决于两个数中的较小者。初始时,我们在数组的起点和终点分别设置两个指针,循环的每一步计算当前矩形的面积并更新最大面积,然后移动较小值的指针缩小矩形宽度进入下一循环。该算法只需要一层循环即可计算出最大的矩形面积,时间复杂度O(n),空间复杂度O(1),算法的大体过程如下图:

代码如下:

public class Solution {
    public int maxArea(int[] height) {
        
        int maxarea = 0, l = 0, r = height.length - 1;
        while (l < r) 
        {
            maxarea = Math.max(maxarea, Math.min(height[l], height[r]) * (r - l));
            if (height[l] < height[r])
                l++;
            else
                r--;
        }
        return maxarea;
    }
}
上一篇下一篇

猜你喜欢

热点阅读