前言
本文介绍了 LeetCode 第 11 题 , “Container With Most Water”, 也就是 “盛最多水的容器” 的问题.
本文使用 C# 语言完成题目。
题目
English
LeetCode 11. 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 and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
中文
LeetCode 11. 盛最多水的容器
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
解决方案
分析题目可知,由下标 i
,j
( j > i )
的组成的容器可容纳水的面积为 (j-i)*Min( height[i] , height[j] )
,其中 j-i
表示容器底边的长度, Min(height[i],height[j])
表示容器的高,要想容纳更多的水,则需要底边的值相对比较大、同时高的值也相对比较大,对于底边和高来说,底边的长度更容易控制,因为我们取最左边和最右边的线时,底边的值是最大的。
容器面积的高取决于两条线中较矮的那条。 假设height.len=10
, 我们先令i=0
,j=9
,然后计算面积并记录下来。此时容器的底边是最长的,若i
,j
向中间移动了,底边的长度就会变小,若想面积增大,则必须高增大才行,所以我们需要比较 height[0]
和 height[9]
,取较短的一条线,使之向中间移动直到找到更长的一条线,才有可能使得容器面积变大。
但由于求面积的代码并不复杂,所以 较短的一条线在移动时,也没必要 找到更长的线,只需要直接向中间移动一位并求面积 即可。
参考代码:
public int MaxArea(int[] height)
{
int max = 0;
int i = 0, j = height.Length - 1;
while (i < j)
{
int area = (j - i) * Math.Min(height[i], height[j]);
if (area > max) max = area;
if (height[i] < height[j]) i++;
else j--;
}
return max;
}
执行结果
执行结果 通过。 执行用时: 116ms, 内存消耗 27.5M
复杂度分析
时间复杂度:O(n)
最坏情况下,i
和 j
共同把 height数组遍历一遍。
空间复杂度:O(1)
仅几个变量来存值。
参考资料汇总
题目:
https://leetcode-cn.com/problems/container-with-most-water/
官方题解: