題目
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.
思路
代碼
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;
}
}