11. Container With Most Water
2016-10-25 10:37
351 查看
题目:Container With Most Water
原题链接:https://leetcode.com/problems/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.
给出一组非负整数来表示一组点,数组下标用来表示横坐标,元素值表示纵坐标,每个点与X轴练成一条线,从中任意去两个点的线段与X轴组成一个梯形容器来容水,求最大的容水量。
注意不能倾斜容器。
容器的容量由梯形短的那条边决定。设梯形在X轴上的长度为宽,Y轴上的短边为高,首先选取最宽的点,即数组的第一个点(i = 0)和最后一个点(j = height.size() - 1 ),计算容量,然后往里面收缩,因为宽变小了,所以之后收缩的时候遇到高比原来的矩形高的时候才有可能出现更大的容量,然后一直收缩到i >= j为止。
代码如下:
class Solution { public: int maxArea(vector<int>& height) { int i = 0, j = height.size() - 1, ret = 0; while(i < j) { int h = min(height[i], height[j]); ret = max(ret, (j - i) * h); while(height[i] <= h && i < j) i++; while(height[j] <= h && i < j) j--; } return ret; } };
相关文章推荐
- LeetCode 11 Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- [Leetcode] 11 Container With Most Water
- leetcode-11 Container With Most Water
- 11. Container With Most Water
- leetcode11 Container With Most Water
- 11 Container with most water
- LeetCode之11---Container With Most Water
- 11. Container With Most Water
- 思维题(两点逼近)LeetCode11 Container with Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- LeetCode 11 Container With Most Water
- 第三周:11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- leetcode note--leetcode 11 Container With Most Water
- 11. Container With Most Water
- leetcode-11 Container With Most Water