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

《leetCode》:Container With Most Water

2015-11-16 21:55 323 查看

题目

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.


题目大意:使容器装更多的水

思路一:暴力搜索法

寻找体积最大,容器的体积由两个高度中较低的高度和圆底的半径决定:

area=min(height[i],height[j])*(j-i)

实现代码如下:

int min(int a,int b){
return a<=b?a:b;
}
int maxArea(int* height, int heightSize) {
if(height==NULL||heightSize<1){
return 0;
}
int max=0;
for(int i=0;i<heightSize;i++){
for(int j=i+1;j<heightSize;j++){
int area=min(height[i],height[j])*(j-i);
if(area>max){
max=area;
}
}
}
return max;
}


时间复杂度为O(n^2),报超时错误。因此需要寻找更好的方法来实现。

思路二

思路:

一个容器装水只能由两个高度中最低的高度作为容器的高度。

如果我们从两个数相隔最远的长度(即第一个和最后一个元素),那么我们将得到一个最大宽度的矩形。

现在,我们可以移动高度较小的那个高度(即较少宽度,但是高度可能增加,这样总面积可能也会增加),来获取最大的总面积

这种思路的时间复杂度为O(n)

int min(int a,int b){
return a<=b?a:b;
}
int maxArea(int* height, int heightSize) {
if(height==NULL||heightSize<1){
return 0;
}
int max=0;
int begin=0;
int end=heightSize-1;
while(begin<end){
int area=min(height[begin],height[end])*(end-begin);
if(area>max){
max=area;
}
if(height[begin]>height[end]){
end--;
}
else {//if(height[begin]<=height[end])
begin++;
}
}

return max;
}


AC结果如下:

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