From a952faff55a36999dc5cb283b4df6d952b864914 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Sat, 8 Dec 2018 12:41:48 +0800 Subject: [PATCH] Create 11. Container With Most Water.md --- 11. Container With Most Water.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 11. Container With Most Water.md diff --git a/11. Container With Most Water.md b/11. Container With Most Water.md new file mode 100644 index 0000000..4fcd22f --- /dev/null +++ b/11. Container With Most Water.md @@ -0,0 +1,24 @@ +# [11. Container With Most Water](https://leetcode.com/problems/container-with-most-water/) +# 思路 +题意就是选择两条线,使其组成的容器装的水最多。水的量可以用宽乘高计算。 +由于宽最大就是height两端之间的距离,所以要想在两端之内取得最大值的话只能是高度比较高。 +可以考虑设置两个初始分别为两端的指针left和right代表当前容器,不断跳过高度不够高的height使这两个指针往中间靠。这个过程不断循环即可得到结果。 +时间复杂度O(n),空间复杂度O(1) + +# C++ +``` C++ +class Solution { +public: + int maxArea(vector& 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++; // 跳过高度不够高的 + while(height[right] <= h) right--; + } + return res; + } +}; +```