首先看题目:
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.
意思是,有一个非负数的数组,数组中每个元素就是一条垂直的线,这条线的两端坐标是(i,ai),( i,0),i是数组元素的下标,
选取两条组成面积最大的,计算出值,注意,矩形不能倾斜,,,
1499077569(1).jpg
如上图。
从java代码解决,直接上代码
/**
* Created by Wangjianxin on 2017/7/3 0003.
*/
public class ContainerWithMostWater {
public int maxArea(int[] height) {
int oldmax = 0;
int newmax = 0;
int len = height.length;
int left = 0;
int right = len - 1;
while (left < right){
//计算面积,看上图可以知道,需要两条线中短线的高,和两线之间的距离宽
if(height[left] > height[right]){
oldmax = height[right] * (right - left);
}else {
oldmax = height[left] * (right - left);
}
if(newmax < oldmax){
newmax = oldmax; //得到最大值
}
//这里用于从两头往中间一直计算,只要两条线中壹条短一些, 就应该在那条短的线继续向前或者向后的其他线在计算
if(height[left] > height[right]){
right --;
}else {
left ++;
}
}
return newmax;
}
}












网友评论