11. 盛最多水的容器
# 11. 盛最多水的容器 (opens new window)
# 1.双指针
解题思路:头尾双指针遍历搜索。核心关键是判断哪个指针移动,由于总蓄水量由两端纳水量更小的水管和水管数目来决定,因此如果移动纳水量更大的指针,那么后续的最小纳水量只会比当前的结果小,同时水管数目一直不断变小,最终搜索到到的总蓄水量只会比当前结果小。
综上讨论,要搜索到更大蓄水量的结果,只能移动纳水量更小的那一端指针,每次更新整个水池的下限后,都更新总蓄水量。
class Solution {
public int maxArea(int[] height) {
int left=0;
int right=height.length-1;
int ans=Math.min(height[left],height[right])*(right-left);
while(left<right){
int min=Math.min(height[left],height[right]);
//移动左端
if(height[left]<height[right]){
while(left<right&&height[left]<=min){
left++;
//找到新的下界
if(left<right&&height[left]>min){
int temp=Math.min(height[left],height[right])*(right-left);
ans=temp>ans?temp:ans;
break;
}
}
}
//移动右端
else{
while(left<right&&height[right]<=min){
right--;
//找到新的下界
if(left<right&&height[right]>min){
int temp=Math.min(height[left],height[right])*(right-left);
ans=temp>ans?temp:ans;
break;
}
}
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57