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

11. Container With Most Water

2018-03-13 08:57 399 查看

问题描述

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.

题目链接:

思路分析

给一个高度的数组,使得形成的容器的容积最大。

容积 = min(height) * abs(i - j)。正常的暴力破解O(n)会TLE,所以我们假定一开始相距最远的两根形成的container的容积是最大的,而指针移动的条件则是不断的去寻找更高的height,因为更高的height才能保证弥补i和j之间的差距,逐步向中间靠近。

代码

class Solution {
public:
int maxArea(vector<int>& height) {
int maxArea = 0, low = 0, high = height.size() - 1;
while (low < high){
maxArea = max(maxArea, min(height[low], height[high])*(high - low));
if (height[low] < height[high])
low++;
else
high--;
}
return maxArea;
}
};


时间复杂度:O(n)

空间复杂度:O(1)

反思

很巧妙的方法,也不像动态规划,但是非常有效。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: