Container With Most Water
2016-07-31 19:50
344 查看
一、问题描述
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.
二、思路
本题难点在于理解题目。在二维坐标系中,求(i,0)(j,0)组成的线段乘以高度h组成的图形面积最大,是一道动态规划题目,我们可以采用双层for求解,但是那样显然不是最优的,我们采用两个指针,一前一后找到最大值存起来,如果当前的权值小于h,那么没必要计算,直接跳过,最后返回最大值。
三、代码
class Solution {
public:
int maxArea(vector<int>& height) {
int water = 0;
int i = 0, j = height.size() - 1;
while(i < j){
int h = min(height[i],height[j]);
water = max(water,(j - i) * h);
while(height[i] <= h && i < j) i++;
while(height[j] <= h && i < j) j--;
}
return 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.
二、思路
本题难点在于理解题目。在二维坐标系中,求(i,0)(j,0)组成的线段乘以高度h组成的图形面积最大,是一道动态规划题目,我们可以采用双层for求解,但是那样显然不是最优的,我们采用两个指针,一前一后找到最大值存起来,如果当前的权值小于h,那么没必要计算,直接跳过,最后返回最大值。
三、代码
class Solution {
public:
int maxArea(vector<int>& height) {
int water = 0;
int i = 0, j = height.size() - 1;
while(i < j){
int h = min(height[i],height[j]);
water = max(water,(j - i) * h);
while(height[i] <= h && i < j) i++;
while(height[j] <= h && i < j) j--;
}
return water;
}
};
相关文章推荐
- LeetCode之11---Container With Most Water
- LeetCode:Container With Most Water
- Container With Most Water
- LeetCode 11---Container With Most Water
- Array(9) -- Container With Most Water,Insert Delete GetRandom O(1) I, II
- **Leetcode_container-with-most-water(c++ and python version)
- [leetcode] Container With Most Water
- Container With Most Water 解答
- leetcode Container With Most Water
- LeetCode Container With Most Water
- [Leetcode] Container With Most Water
- leetcode container with most water
- 11. Container With Most Water
- 【LeetCode】Container With Most Water
- 【Leetcode】Container With Most Water
- LeetCode - Container With Most Water
- LeetCode 11 Container With Most Water
- Container With Most Water
- LeetCode 011 Container With Most Water
- Container With Most Water