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.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
注:这道题好评率挺高,因为下午温习了下 python 基础所以开始的时候用 python
写的。知道 python 慢,但是不知道是这么的慢。因为时间复杂度是O(n^2),所以直接超时了。只能再改成Java的,时间也达到了350ms。
1.Java 版
class Solution {
public int maxArea(int[] height) {
int length = height.length;
int h,l;
int result = 0;
if(length < 2)
return 0;
for(int i = 0; i < length-1; ++i)
for(int j = i+1; j < length; ++j){
if(height[i] > height[j])
h = height[j];
else
h = height[i];
l = h*(j-i);
if(result < l)
result = l;
}
return result;
}
}
2.python版
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
if len(height) < 2:
return 0
result = 0
for i in range(len(height) - 1):
for j in range(i + 1,len(height)):
if height[i] >= height[j]:
h = height[j]
else:
h = height[i]
l = j - i
if h*l > result:
result = h * l
return result