Skip to content

Commit 96772ad

Browse files
author
binbin.hou
committed
[Feature] add for new
1 parent 1f6154d commit 96772ad

File tree

1 file changed

+146
-0
lines changed

1 file changed

+146
-0
lines changed
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
---
2+
title: LC11. 盛最多水的容器 container-with-most-water
3+
date: 2025-08-31
4+
categories: [Leetcode-75]
5+
tags: [leetcode, Leetcode-75, two-pointer]
6+
published: true
7+
---
8+
9+
# LC11. 盛最多水的容器 container-with-most-water
10+
11+
给定一个长度为 n 的整数数组 height。
12+
13+
有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
14+
15+
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
16+
17+
返回容器可以储存的最大水量。
18+
19+
说明:你不能倾斜容器。
20+
21+
示例 1:
22+
23+
![1](https://aliyun-lc-upload.oss-cn-hangzhou.aliyuncs.com/aliyun-lc-upload/uploads/2018/07/25/question_11.jpg)
24+
25+
输入:[1,8,6,2,5,4,8,3,7]
26+
输出:49
27+
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
28+
29+
示例 2:
30+
31+
输入:height = [1,1]
32+
输出:1
33+
34+
35+
提示:
36+
37+
n == height.length
38+
2 <= n <= 10^5
39+
0 <= height[i] <= 10^4
40+
41+
42+
43+
44+
45+
# v1-双指针
46+
47+
## 思路
48+
49+
两个指针,left=0, right=n-1
50+
51+
好处是这样保障宽度最大,高度就是 `min(height[left], height[right])`
52+
53+
问题是,左右如何移动呢?
54+
55+
其实就是保留高度最大的一边,移动另一边即可,尽可能的让面积最大。
56+
57+
## 实现
58+
59+
```java
60+
public int maxArea(int[] height) {
61+
int left = 0;
62+
int right = height.length-1;
63+
64+
int max = 0;
65+
while(left < right) {
66+
int leftH = height[left];
67+
int rightH = height[right];
68+
int w = right - left;
69+
int h = Math.min(leftH, rightH);
70+
71+
int area = w*h;
72+
max = Math.max(area, max);
73+
74+
// 左右移动
75+
if(leftH > rightH) {
76+
right--;
77+
} else {
78+
left++;
79+
}
80+
}
81+
82+
return max;
83+
}
84+
```
85+
86+
## 效果
87+
88+
4ms 击败 75.48%
89+
90+
## 复杂度
91+
92+
TC: O(n)
93+
94+
## 反思
95+
96+
这个解法应该是理论最优,为什么不是 100%?
97+
98+
# v2-剪枝优化
99+
100+
## 思路
101+
102+
看了眼最佳解法,实际上是对 v1 进行优化。
103+
104+
如果后续的高度和不能高于当前的高度,那么就可以忽略掉。
105+
106+
目的是为了避免多余的计算。
107+
108+
## 实现
109+
110+
```java
111+
public int maxArea(int[] height) {
112+
int left = 0;
113+
int right = height.length-1;
114+
115+
int max = 0;
116+
while(left < right) {
117+
int leftH = height[left];
118+
int rightH = height[right];
119+
int w = right - left;
120+
int h = Math.min(leftH, rightH);
121+
122+
int area = w*h;
123+
max = Math.max(area, max);
124+
125+
// 左右移动
126+
while(height[left] <= h && left < right) {
127+
left++;
128+
}
129+
while(height[right] <= h && left < right) {
130+
right--;
131+
}
132+
}
133+
134+
return max;
135+
}
136+
```
137+
138+
## 效果
139+
140+
1ms 100%
141+
142+
## 反思
143+
144+
整体的逻辑不变,但是追求极致,令人赞叹的算法。
145+
146+
# 参考资料

0 commit comments

Comments
 (0)