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

leetcode习题解答:11. Container With Most Water

2017-10-26 13:21 393 查看
难度:Medium

链接

描述:

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.
注:返回的是最大面积

解题思路:

第一个想到的就是列举了吧,双重循环来找这个最大面积,当然,这样时间复杂度为O(n^2),耗时感人。下面有一个稍微改进的,二层循环从数组尾端向前扫描,可以排除一些情况,加快速度。

class Solution {
public:
int maxArea(vector<int>& height) {
int max = 0;
for(int i = 0; i < height.size(); i++){
int h = 0;
for (int k = height.size()-1; k >= i+1; k--){
if (height[k] > height[i]){
int m = height[i]*(k-i);
if (m > max)max = m;
break;
} else if (height[k] > h){
int h = height[k];
int m = h*(k-i);
if (m > max)max = m;
}
}
}
return max;
}
};

但是这肯定不是最好的算法,可以有这么一种思路,从数组两端向中间逼近,但是要怎样设置条件呢?
我们知道计算面积,height取的是两边的最小值,那么如果出现一边比较高的时候比如height[left] > height[right],left可以不改动,而right--来寻找一个更高的height,如果right

比较高,那么left++去寻找一个更高的height,这样不断计算面积,最后就能得出最大面积。

class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right = height.size()-1;
int max = 0;
while(left < right){
int minHeight = height[left]<height[right]?height[left]:height[right];
int newMax = (right-left)*minHeight;
if (newMax > max) max = newMax;
if (height[left] < height[right])
left++;
else
right--;
}
return max;
}
};

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