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

Leetcode -- Container With Most Water

2015-08-11 15:23 513 查看
题目:

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.

分析:若干条线,找两条线使得其与X轴围成的面积最大。

如果是暴力的穷搜,肯定可以得到答案,但复杂度达到O(N^2),耗时,leetcode里面是过不去的。

思路:从数据集的两头同时开始。当ai小于aj时,i ++; 反之,j–。直到二者相遇。理由,影响面积的是比较短的线,因此,每次只要改变比较短的线就好了。这个想法的复杂度是O(N)

代码:

int maxArea(vector<int>& height) {
int len = height.size();
int max_area = 0, area = 0;

int i = 0, j = len - 1;
while(i < j)
{
if(height[i] < height[j])
{
area = (j -i) * height[i];
i ++;
}
else
{
area = (j - i) * height[j];
j --;
}
if (area > max_area)
{
max_area = area;
}
}
return max_area;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息