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

【Leetcode长征系列】Container With Most Water

2014-07-23 16:30 375 查看
原题:

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.

思路:最开始的思路是,两个指针指向height中一前一后的元素直到最后,分别求出其面积比较保留下最大值即可。

代码如下:

class Solution {
public:
int maxArea(vector<int> &height) {
int max = 0;
for(int i=0; i< height.size(); i++)
for(int j=i+1; j<height.size(); j++)
max = max > (j-i)*min(height[i],height[j])?max:(j-i)*min(height[i],height[j]);
return max;
}
};很遗憾,它超时了。



因为我这个算法的时间复杂度达到O(N*N),所以换一个算法试试。

思路2:

两个指针一个指头一个指尾。我们需要比较的是(j-i)*min(height[i],height[j]),所以两个指针一首一尾在不相遇之前我们可以保证最后的结果是(j-i),并且这个值一定是在递减的!所以为了保证我们得到最大面积,我们就要想办法找到最大的短板。

class Solution {
public:
int maxArea(vector<int> &height) {
int max = 0;
int begin = 0;
int end = height.size()-1;

while(begin!=end){
max = max>min(height[begin],height[end])*(end-begin)?max:min(height[begin],height[end])*(end-begin);
if(height[begin]<height[end]) begin++;
else end--;
}
return max;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: