您的位置:首页 > 大数据 > 人工智能

[LeetCode]Container With Most Water

2017-06-08 07:48 357 查看
Description:

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.

解析:这道题的题意是,有n条竖线(隔板),求任意两条竖线与x轴组成的木桶的面积。实际上就是哪两个木板组成的面积最大。

这道题第一眼看去就抛去了暴力手法,太麻烦了,而且时间复杂度肯定不够,所以得找到技巧(规律)。这道题找出规律就好做了。

当你在纸上画图,然后慢慢观察的时候,你会发现:假设两条木板L,R(R是离L最远的一条木板)。如果L < R,那么对于L来说,他能组成最大的面积就是(R-L)乘L。其它的任何木板组成的面积都是(R-L-n)乘L。

这样的话,我们就不需要一个一个比较了,代码也就出来了。

code:

public int maxArea(int[] height) {

if(height == null)return 0;

int len = height.length-1;
int index = 0;
int area = 0;
int temp = 0;
while(index < len){
if(height[index] < height[len]){
temp = (len-index)*height[index];
index++;
}
else{
temp = (len-index)*height[len];
len--;
}

if(area < temp){
area = temp;
}
}
return area;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode