LeetCode OJ-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.
题目理解
装的水的量,定义为两条直线中较短的一直线的长度与两直线纵坐标的差值的乘积。若不考虑超时,可以用最直接的方法,最外层循环迭代第1条直线的位置,内层循环迭代第2条直线的位置,依次求面积。但这样是AC不了的,所以就要考虑其他办法了。
先看装水量的计算,装水量仅与两直线中较短的一条与横坐标差值有关,也就是说,要使装水量更大,可以选择提升短板,或者增大两直线横坐标差值,因为有两个未知量没有别的条件,处理不了,所以我们需要限定其中一个条件,这里我们使用两个迭代器,分别指向i=0与j=vec.size() - 1,如此,在移动迭代器时,横坐标差值是在减小的,只要短板被提升,装水量就有可能被提升,但如果提升较长的直线,对装水量是不会有任何提升的。在两迭代器向中心移动的过程中,及时更新max_area即可。具体代码如下:
Code
#define MAX(m, n) ( (m > n) ? m : n )
#define MIN(m, n) ( (m < n) ? m : n )
class Solution {
public:
int maxArea(vector<int>& height) {
int max = 0;
int sz = (int) height.size();
int i = 0;
int j = sz - 1;
while (i < j) {
max = MAX(max, (MIN(height[i], height[j]) * (j - i)));
if (height[i] < height[j]) {
++i;
}
else {
--j;
}
}
return max;
}
};