作者:梦里的天真575 | 来源:互联网 | 2024-09-30 18:33
Level:
??Medium
题目描述:
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
思路分析:
??从两端往中间搜索,面积的计算方法为两端中较小的作为高,坐标差作为宽,然后求积就是面积,时间复杂度为O(n)。
代码:
public class Solution{
public int maxArea(int []height){
int i=0; //左端
int j=height.length-1;
int maxarea=Math.min(height[i],height[j])*(j-i);
while(i if(height[i]<=height[j])
i++; //为什么要i++而不是j++,因为要尽可能保留高度高的
else
j--;
int area=Math.min(height[i],height[j])*(j-i);
maxarea=Math.max(maxarea,area);
}
return maxarea;
}
}