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

【LeetCode】Container With Most Water

2013-10-12 10:22 288 查看
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.
这题有点像直方图中最大矩形面积,刚开始就看错了,结果不一样,O(n)的算法是看了网上一个大牛的:

class Solution {
public:
int maxArea(vector<int> &height) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int size = height.size();
int ld = 0, rd = size - 1;
int res = 0;
if(size <= 1)
return 0;
while(ld < rd)
{
int h = height[ld] < height[rd] ? height[ld] : height[rd];
res = max(res,h*(rd-ld));
if(height[ld] < height[rd])
ld++;
else rd--;
}
return res;
}
};

来一个java的,最近在研究java:

public class Solution {
public int maxArea(int[] height) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int size = height.length;
int ld = 0, rd = size - 1;
int res = 0;
while(ld < rd)
{
int h = height[ld] < height[rd] ? height[ld] : height[rd];
res = Math.max(res,h*(rd-ld));
if(height[ld] < height[rd])
ld++;
else rd--;
}
return res;

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