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

LeetCode OJ - Container With Most Water

2014-07-01 11:20 337 查看
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.

思路一:常规思路先采用一维迭代,若a[i - 1] < a[i] 不能立马确定能盛多少水,因为i - 1前面可能有介于a[i - 1] 和 a[i]的数,找出来并判断。这样思考发现规律性不强,解起来没完没了因为每做一次判断都需要考虑全局情况。

对于这类问题,可以考虑的思路有:

1.双向迭代

2.维护局部最值,采用贪心策略

3.迭代形式的dp

思路二:没读清楚题目,开始以为是能盛多少水,题目要求是找出两根线和x轴,判断最大能盛水数。 但是发现总共能盛多少水这个问题,也很好玩,因为每次的当前状况都跟历史有关,如果每次遍历历史,则总的时间复杂度为O(n^2)。这里我采用了双向迭代,求出了所有能盛的水量。时间复杂度为线性时间复杂度。

int maxArea(vector<int> &height) {
int len = height.size();
if(len < 2) return 0;

int ret = 0;
int i, j;
//正向迭代
i = 0;
while(1) {
for(j = i + 1; j < len; j++) {
if(height[j] >= height[i]) {
ret+= (j - i) * height[i];
break;
}
}
if(j == len) break;
i = j;
}
//逆向迭代
i = len - 1;
while(1) {
for(j = i - 1; j >= 0; j--) {
if(height[j] > height[i]) {
ret += (i - j) * height[i];
break;
}
}
if(j < 0) break;
i = j;
}

return ret;
}

思路三:终于读懂了题目,不过这个题目不就跟Largest
Rectangle in Histogram一样了吗,求出坐标中的最大矩形。

题意是有个高度数组,就相当于隔板的高度,求数组中任意两隔板间盛水的最大量。隔板间的距离与较低隔板的高度乘积即为盛水的容量。

这里采用的是两边逼近办法,假设两个挡板在中间,从外围开始想办法收敛到那两个挡板。

class Solution {
public:
int maxArea(vector<int> &height)
{
int len = height.size();
if(len < 2) return 0;

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