https://oj.leetcode.com/problems/container-with-most-water/
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 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.
解题思路:
这是一道很巧妙的题目。根据短板原理,这个容器能容的水量,应该是两个很坐标的差,也就是宽,乘以两个竖线中较短的那个。如果使用暴力法,显然需要对比n个竖线两两的组合,时间复杂度为O(n^2)。一般的,这样的解法都会超时,必须要寻找更为好的方法。
我们这里使用两个游标,分别指向a1和an,向中间靠近,直到两者相等。如果左侧的小,则左侧坐标++,如果右侧小,则右侧坐标--。考虑一下为什么这样就可以了?
还是因为面积是由宽和较短的那根竖线决定的。如果左侧的较短,右侧再往内收,宽就更小,竖线也不会超过左侧的高度了,反而可能更低,显然已经到了最大值。所以只能将左侧的竖线内收,右侧不动。寻找在宽变小的情况下,可能的更长的竖线。
这道题用了两个pointers,在线性时间内就得到了解,值得好好体会。
public class Solution { public int maxArea(int[] height) { int max = 0; int start = 0; int end = height.length - 1; while(start < end){ max = Math.max(max, (end - start) * Math.min(height[start], height[end])); if(height[start] < height[end]){ start ++; }else{ end--; } } return max; } }