一【题目类别】
二【题目难度】
三【题目编号】
四【题目描述】
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 说明:你不能倾斜容器。
五【题目示例】
示例 1: 输入:[1,8,6,2,5,4,8,3,7] 输出:49 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 示例 2: 输入:height = [1,1] 输出:1 示例 3: 输入:height = [4,3,2,1,4] 输出:16 示例 4: 输入:height = [1,2,1] 输出:2
六【题目提示】
n
=
h
e
i
g
h
t
.
l
e
n
g
t
h
n = height.length
n = h e i g h t . l e n g t h
2
<
=
n
<
=
3
∗
1
0
4
2 <= n <= 3 * 10^4
2 < = n < = 3 ∗ 1 0 4
0
<
=
h
e
i
g
h
t
[
i
]
<
=
3
∗
1
0
4
0 <= height[i] <= 3 * 10^4
0 < = h e i g h t [ i ] < = 3 ∗ 1 0 4
七【解题思路】
双指针,一个指向开始一个指向结尾,此时底最大,如果高也最大就会是最大容量,但是当移动指针时会伴随着底变小,所以我们要想办法让高变大,这样容积才能最大,既然我们要高最大,所以就移动高小的那个指针就可以,这样就保留了较高的一端,放弃了较矮的一端,就能保证容积可以变大,值得注意的一点是,计算容积的时候计算的是较矮的一段的高度,否则液体会溢出,其实里面有贪心的思想,就是每次移动我们都要得到最大的容量
八【时间频度】
九【代码实现】
Java语言版
package Array;
public class p11_ContainerWithMostWater {
public static void main ( String[ ] args) {
int [ ] height = { 1 , 8 , 6 , 2 , 5 , 4 , 8 , 3 , 7 } ;
int res = maxArea ( height) ;
System. out. println ( "res = " + res) ;
}
public static int maxArea ( int [ ] height) {
int leftIndex = 0 ;
int rightIndex = height. length - 1 ;
int res = 0 ;
while ( leftIndex < rightIndex) {
res = height[ leftIndex] < height[ rightIndex] ? Math. max ( res, ( rightIndex - leftIndex) * height[ leftIndex++ ] ) : Math. max ( res, ( rightIndex - leftIndex) * height[ rightIndex-- ] ) ;
}
return res;
}
}
C语言版
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int MAX ( int x, int y)
{
if ( x > y)
{
return x;
}
return y;
}
int maxArea ( int * height, int heightSize)
{
int leftIndex = 0 ;
int rightIndex = heightSize - 1 ;
int res = 0 ;
while ( leftIndex < rightIndex)
{
res = height[ leftIndex] < height[ rightIndex] ? MAX ( res, ( rightIndex - leftIndex) * height[ leftIndex++ ] ) : MAX ( res, ( rightIndex - leftIndex) * height[ rightIndex-- ] ) ;
}
return res;
}
十【提交结果】
Java语言版 C语言版