题目
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.
思路
大意是数组下标i和非负数组值a[i]
组成一个坐标点(i, a[i]),要找出两条纵线和x轴组成一个容器,使得容器能容纳最多水(不能“倾斜”该容器)。假设有(i, a[i])和(j, a[j])两个坐标(j > i),容积取决于min(a[i],a[j]) * (j - i)。
采用两层循环嵌套肯定是不能通过的,因为时间复杂度为o(n^2),输入大数组时严重超时。采用从两端向中间靠拢的办法,即 j - i 的值逐渐减小,这时高肯定要增大才可能取得更大的面积,按照这种思路不断更新i和j的值(i增大或者j减小),直到不满足i < j 时就能得到最优解。
代码
Python
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i = 0
j = len(height) - 1
res = 0
while(i < j):
res = max(res,min(height[i],height[j])*(j-i))
if(height[i] < height[j]):
k = i
while (k < j) and (height[k] <= height[i]):
k += 1
i = k
else:
k = j
while (k > i) and (height[k] <= height[j]):
k -= 1
j = k
return res
Java
public class Solution {
public int maxArea(int[] height) {
int res = 0;
int i = 0;
int j = height.length - 1;
int k;
if (j < 1) return 0;
//从两端向中间靠拢,找出比两端的线高的位置
while (i < j){
res = Math.max(res,Math.min(height[i], height[j])*(j - i));
//左低右高,则找出最靠近i且比height[i]高的位置
if (height[i] < height[j]){
for(k = i;k < j && height[k] <= height[i];k++);
i = k;
}
//右低左高,则找出最靠近j且比height[j]高的位置
else{
for(k = j;k > i && height[k] <= height[j];k--);
j = k;
}
}
return res;
}
}