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

【Leetcode】Container With Most Water

2014-03-19 19:21 363 查看
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.

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


View Code
容器的容积 C = min(ai, aj) * (j - i) (这里令 j > i) 。

从两边向中间夹逼扫描,所以第一个计算的是 j = n - 1, i = 0;

那么在夹逼的过程中,什么时候应该左指针向右,什么时候右指针向左呢?

回到容积计算公式,两边向中间扫描的过程中,因式中的(j - i)项一定是变小了,所以只有min(ai, aj)项增大才可能使得容积变大。所以应该当ai小的时候,右移左指针,aj小的时候左移右指针,检查下一个可能使得容积变大的容器。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: