LeetCode 11. Container With Most Water

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;
    }
}
原文地址:https://www.cnblogs.com/liangyongrui/p/6483818.html