LeetCode/solutions/11. Container With Most Water.md
ShusenTang 17fdd4c39a
fix 11
2023-02-18 11:29:54 +08:00

27 lines
1.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [11. Container With Most Water](https://leetcode.com/problems/container-with-most-water/)
# 思路
题意就是选择两条线,使其组成的容器装的水最多。水的量可以用宽乘高计算。
由于宽最大就是height两端之间的距离所以要想在两端之内取得最大值的话只能是高度比较高。
可以考虑设置两个初始分别为两端的指针left和right代表当前容器不断跳过高度不够高的height使这两个指针往中间靠。这个过程不断循环即可得到结果。
时间复杂度O(n)空间复杂度O(1)
> 注意不要把此题和[42. Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/)题搞混了!!
# C++
``` C++
class Solution {
public:
int maxArea(vector<int>& height) {
int res = 0;
int left = 0, right = height.size() - 1;
while(left < right){
int h = min(height[left], height[right]); // 当前容器高度
res = max(res, h * (right - left));
while(height[left] <= h && left < right) left++; // 跳过高度不够高的
while(height[right] <= h && left < right) right--;
}
return res;
}
};
```