【LeetCode】11. Container With Most Water - Java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoguaihai/article/details/84095342

1. 题目描述:

Given n non-negative integers a[1], a[2], …, a[n] , where each represents a point at coordinate (i, a[i]). n vertical lines are drawn such that the two endpoints of line i is at (i, a[i]) 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 and n is at least 2.

示例图

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

2. 思路分析:

题目的意思是找两条竖线然后这两条线以及X轴构成的容器能容纳最多的水。

最简单粗暴的方式是两两遍历的双重循环做法,算出所有可能情况,返回最大的。但这种方式时间复杂度是O(n^2),太慢了。

寻求更简单的解法的思路就是省去没有必要的遍历,并且确保所需的答案一定能被遍历到。

假设现在有一个容器,则容器的盛水量取决于容器的底和容器较短的那条线,则我们可以从最长的底入手,即当容器的底等于数组的长度时,则容器的盛水量为较短边的长乘以底。可见 只有较短边会对盛水量造成影响,因此移动较短边的指针,并比较当前盛水量和当前最大盛水量。直至左右指针相遇。时间复杂度是O(n)。

主要的困惑在于如何移动双指针才能保证最大的盛水量被遍历到?
假设有左指针left和右指针right,且a[left] < a[right],假如我们将右指针左移,则右指针左移后的值和左指针指向的值相比有三种情况:

  • a[left] < a[right’]
    这种情况下,容器的高取决于左指针,但是底变短了,所以容器盛水量一定变小;
  • a[left] == a[right’]
    这种情况下,容器的高取决于左指针,但是底变短了,所以容器盛水量一定变小;
  • a[left] > a[right’]
    这种情况下,容器的高取决于右指针,但是右指针小于左指针,且底也变短了,所以容量盛水量一定变小了;

综上所述,容器高度较大的一侧的移动只会造成容器盛水量减小;所以应当移动高度较小一侧的指针,并继续遍历,直至两指针相遇。

3. Java代码:

源代码见我GiHub主页

代码:

public static int maxArea(int[] height) {
    int maxArea = 0;
    int l = 0;
    int r = height.length - 1;
    while (l < r) {
        int curArea = Math.min(height[l], height[r]) * (r - l);
        maxArea = Math.max(maxArea, curArea);
        if (height[l] < height[r]) {
            l++;
        } else {
            r--;
        }
    }
    return maxArea;
}

猜你喜欢

转载自blog.csdn.net/xiaoguaihai/article/details/84095342