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

LeetCode--Container With Most Water

2017-09-29 19:40 447 查看
题目:

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.

解读:给予一组非负整数a1、a2....an,对应平面坐标系中的点(i,ai),i-ai表示 从 (i, 0) 到 (i, ai) 的一条线段,两条线段和 x 轴组成一个木桶,找出能够盛水最多的木桶,返回其容积。木桶的容积取决于两条线段之间的长度和较短的线段的高度。

思考:如果采用双重循环的遍历则超时。如果能够边遍历边排除则可降低计算量。

两个线段分别指向最左和最右,下标用left和right标识,如果左边的线段小于右边线段,则保存容积,left++;如果右边的线段小于左边的线段,则保存容积,right--;直到left=right停止,取最大的容量返回。

因为当左<右,容积为左高度*(R底边),左边向右移则排除了left与(R-1)等更小的底边的组合,这些组合的容积均更小。反之亦然。

代码:

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