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

LeetCode 11 Container With Most Water

2015-07-28 21:06 375 查看




Container With Most Water

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.
解法思路:题目大意是以x轴 ,两个以顶点在(i, ai)、(j,
aj)到x轴的垂直直线所围成的凹槽的面积的最大值。



暴力法,O(n^2) 的复杂度,两层循环遍历所有节点,找到最大值。但是明显超时了,因此,需要改进。

在这里设置两个指针,分别从最左边和最右边遍历。然后进行判断,若出现左边低于右边高度时,将左边指针加1.若出现左边高于右边的时候,则右边加1.
这里这样做的原因是,当出现较低的高度的时候,替换这个低的高度,从而遍历寻找高的高度来提高面积。如果以相反的做法,则不能提高面积。
暴力法代码如下:
int maxArea1(int* height, int heightSize){
int max = 0;
for (int i = 0; i < heightSize; i++){
int t = heightSize - 1;
while (t>=i)
{
int h = height[i]>height[t] ? height[t] : height[i];
int temp = (t-i)*h;
if (temp >= max){
max = temp;
}
t--;
}
}
return max;
}


双指针代码如下:复杂度O(n)
int maxArea(int *height, int heightSize){
int max = 0;
int left = 0;
int right = heightSize-1;
while (left < right){
int h = height[left]>height[right] ? height[right] : height[left];
int temp = (right - left)*h;
if (temp >= max){
max = temp;
}
if (height[left] > height[right]){
right--;
}
else{
left++;
}
}
return max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: