个人理解:为很会想到以下时间复杂度为O(n)的思路呢? 由题意可知此题意在比较(i-j)*Height的大小。
本题使i,j分别从两边向中间靠拢,保持了length的单调递减,在length递减的条件下,要比之前的面积大,只有提升height,于是将原本较小的height舍弃,向中间靠拢,看是否有更大的面积。
于是有疑问:你如何确定答案就在收缩的(i,j)对中呢?
是因为,在舍弃较小的height中,只自动舍弃了许多小于当前最大值的方案,(也就是最佳答案不会被舍弃)故选择路线一定会经过最大值的(i,j)对。
原题:
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例:
输入: [1,8,6,2,5,4,8,3,7] 输出: 49
解决办法:
class Solution {
public int maxArea(int[] height) {
int i=1,j=height.length;
int temp=0;
while(i<j){
if(height[i-1]<=height[j-1]){
temp=Math.max(temp,(j-i)*Math.min(height[j-1],height[i-1]));
i++;
}else{
temp=Math.max(temp,(j-i)*Math.min(height[j-1],height[i-1]));
j--;
}
}
return temp;
}
}
1 2 3 4 5 6
1 x ------- o
2 x x
3 x x x
4 x x x x
5 x x x x x
6 x x x x x x
Next we move the left line and compute (2,6)
. Now if the right line is shorter, all cases below (2,6)
are eliminated.
1 2 3 4 5 6
1 x ------- o
2 x x o
3 x x x |
4 x x x x |
5 x x x x x |
6 x x x x x x
And no matter how this o
path goes, we end up only need to find the max value on this path, which contains n-1
cases.
1 2 3 4 5 6
1 x ------- o
2 x x - o o o
3 x x x o | |
4 x x x x | |
5 x x x x x |
6 x x x x x x
Hope this helps. I feel more comfortable seeing things this way.