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;
}
};
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;
}
};
相关文章推荐
- leetcode 11 - Container With Most Water
- leetcode - Container With Most Water
- leetCode-Container With Most Water
- LeetCode-11 Container With Most Water
- [Leetcode] 11 Container With Most Water
- 【leetcode】Container with most water--python实现
- 【Leetcode】【python】Container With Most Water
- Leetcode | Container With Most Water
- leetcode-java.T011_ContainerWithMostWater 找两条竖线然后这两条线以及X轴构成的容器能容纳最多的水
- LeetCode-11~Container with Most Water
- LeetCode:Container With Most Water
- LeetCode Container With Most Water
- leetcode -- Container With Most Water
- [LeetCode] Container With Most Water
- Container With Most Water - Leetcode
- [leetcode] Container with most water
- [Leetcode] #11 Container With Most Water
- leetcode 11 Container With Most Water
- [Leetcode] Container With Most Water
- LeetCode | Container with most water(装最多的水)