LeetCode 011 盛水最多的容器(med)
2021/7/17 昨天写了接雨水的题解心得,今天就写一下与接雨水相似以至于弄混的这道盛水容器题

几根不同高度的柱子,柱子之间有整数个的距离,计算出所能盛最多水的容量。
public class Solution {
public int maxArea(int[] height) {
//先定义左右两个指针,分别指向数组的头和尾
int l = 0;
int r = height.length - 1;
//再定义一个最终返回值max用来表示目前可算得最多可盛的水,area为当前指针所表示容器的水容量
int max = 0;
int area;
while (l < r){
area = Math.min(height[l], height[r]) * (r - l);
max = Math.max(area,max);
if (height[l] <= height[r]) {
l++;
}
else r--;
}
return max;
}
}
做过之后可以理解是很普通的双指针,但是在做出来之前还是一头雾水,双指针貌似还是面试经常问道的题型之一,今后还得多找类似的题进行练习。

浙公网安备 33010602011771号