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

Leetcode题解:11. Container With Most Water

2016-11-03 06:15 288 查看

Leetcode题解:11. Container With Most Water

难度: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.

中文简述

给你一串数组a1,a2….an,其中ai表示坐标系中的 (i,ai)即i位置上的垂直高度,其中每两条竖直的线都能组成一个容器来装水,问其中装水最多的容器的容积是多少

思路

其实根据描述,我们知道容积V=(j-i)*min{ai,aj} (i < j)

所以最简单的一个思路就是暴力找出所有容器的容积,然后比较他们的大小,这样做的时间复杂度为O(n^2)

转换一下思路,由于容器的容积取决于两边相隔距离和两边中较短边的高度。我们可以用贪心算法去化简:

①从最远的一对容器边找起,即i=0,j=n;

②从较短边开始向内搜索,计算容积比较大小。重复②直到i=j;

于是我们就能得到一个时间复杂度为O(n)的算法

class Solution {
public:
int maxArea(vector<int>& height) {
int l=0, r=height.size()-1;
int maxsize = 0;
while(l<r){

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