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

11. Container With Most Water

2018-03-27 14:03 337 查看

11. 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 and n is at least 2.

问题分析

就是找到这个坐标点和x轴组成的竖线作为边界,找到两个边界围成的面积最大!



(图片来源于网络)

如果容器盛水最多

矩形面积最大。

盛水量的多少,由两条垂线中较短的一条决定。

两条垂线中较短一条尽可能长。

所以。我们可以构造代码来实现这个问题了!

class Solution {
public:
int maxArea(vector<int> &h) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int res=0;
int n = h.size();
int l=0,r=n-1;
while(l<r)
{
res=max(res,min(h[l],h[r])*(r-l));
if (h[l]<h[r])
{
int k=l;
while(k<r&&h[k]<=h[l])
k++;
l=k;
}
else
{
int k=r;
while(k>l&&h[k]<=h[r])
k--;
r=k;
}
}
return res;
}
};


参考来源:

作者:NapoleonY

链接:https://www.jianshu.com/p/23e8e3e53abf
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: