categories: leetcode
题目描述
Given n non-negative integers a, a, …, a, where each represents a point at coordinate (i, a). n vertical lines are drawn such that the two endpoints of line i is at (i, a) 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
参考代码
class Solution {
public int maxArea(int[] height) {
int max = 0;
boolean temp;
for(int i = 0,j = height.length - 1;i < j;) {
int h = (height[i] > height[j]) ? height[j] : height[i];
if(h * (j - i)>max) max = h * (j - i);
temp = (height[i] < height[j]) ? true : false;
if(temp) i++;
else j--;
}
return max;
}
}
思路及总结
较为简单的思路就是采用双指针,从两边往中间逼近,并没有什么边界问题,主要是注意在寻找最多水的容器过程中要一直把较深的一边留下,即沿着较小的边界进行移动(因为较小的边界不可能再产生更多的水)。