【Leetcode】Container With Most Water
2014-03-19 19:21
363 查看
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.
View Code
容器的容积 C = min(ai, aj) * (j - i) (这里令 j > i) 。
从两边向中间夹逼扫描,所以第一个计算的是 j = n - 1, i = 0;
那么在夹逼的过程中,什么时候应该左指针向右,什么时候右指针向左呢?
回到容积计算公式,两边向中间扫描的过程中,因式中的(j - i)项一定是变小了,所以只有min(ai, aj)项增大才可能使得容积变大。所以应该当ai小的时候,右移左指针,aj小的时候左移右指针,检查下一个可能使得容积变大的容器。
class Solution { public: int maxArea(vector<int> &height) { int i = 0, j = height.size() - 1; int max_area = 0; while (i < j) { int area = (j - i) * min(height[j], height[i]); if (area > max_area) { max_area = area; } if (height[i] <= height[j]) { ++i; } else { --j; } } return max_area; } };
View Code
容器的容积 C = min(ai, aj) * (j - i) (这里令 j > i) 。
从两边向中间夹逼扫描,所以第一个计算的是 j = n - 1, i = 0;
那么在夹逼的过程中,什么时候应该左指针向右,什么时候右指针向左呢?
回到容积计算公式,两边向中间扫描的过程中,因式中的(j - i)项一定是变小了,所以只有min(ai, aj)项增大才可能使得容积变大。所以应该当ai小的时候,右移左指针,aj小的时候左移右指针,检查下一个可能使得容积变大的容器。
相关文章推荐
- LeetCode Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode No.11 Container With Most Water
- leetcode——Container With Most Water
- LeetCode算法题——Container With Most Water
- [leetcode-11]container with most water(C)
- 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(容器装更多的水)
- LeetCode 141 Container With Most Water
- [leetcode 11] Container With Most Water
- LeetCode--Container With Most Water
- LeetCode之路——Container With Most Water
- LeetCode (11): Container With Most Water
- leetcode 011 —— Container With Most Water
- [LeetCode][Java] Container With Most Water
- LeetCode:Container With Most Water
- leetcode:Container With Most Water