更多题解尽在 https://sugar.matrixlab.dev/algorithm 每日更新。
组队打卡,更多解法等你一起来参与哦!
LeetCode 11. 盛最多水的容器,难度中等。
双指针
解题思路:
- 初始化两个指针,一个指向数组的起始位置
i
,另一个指向数组的末尾位置j
; - 使用一个变量
result
来存储目前找到的最大容积; - 在
i < j
的情况下,计算当前指针所对应的容积,并更新result
; - 移动高度较小的那个指针,尝试找到更大的容积。因为容积的高度是由较短的线段决定的,只有移动较短的线段指针才有可能找到更高的线段,从而增加容积。
class Solution {
public int maxArea(int[] height) {
int result = 0;
int i = 0, j = height.length - 1;
while (i < j) {
result = Math.max(result, Math.min(height[i], height[j]) * (j - i));
if (height[i] < height[j]) {
++i;
} else {
--j;
}
}
return result;
}
}