地址:https://leetcode-cn.com/problems/container-with-most-water/
方法一:暴力解法
枚舉所有的容器的兩個內壁的下標,計算水的容量,選出最大值。
Java 代碼:
public class Solution {
// 暴力解法,時間複雜度太高,我們應該使用指針對撞的方法
public int maxArea(int[] height) {
int len = height.length;
if (len < 2) {
return 0;
}
int res = 0;
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
res = Math.max(res, Math.min(height[i], height[j]) * (j - i));
}
}
return res;
}
public static void main(String[] args) {
int[] height = {1, 8, 6, 2, 5, 4, 8, 3, 7};
Solution solution = new Solution();
int res = solution.maxArea(height);
System.out.println(res);
}
}
方法二:雙指針
Java 代碼:
public class Solution {
public int maxArea(int[] height) {
int len = height.length;
if (len < 2) {
return 0;
}
int left = 0;
int right = len - 1;
int res = 0;
while (left < right) {
int minHeight = Math.min(height[left], height[right]);
res = Math.max(res, minHeight * (right - left));
if (height[left] == minHeight) {
left++;
} else {
right--;
}
}
return res;
}
}
使用雙指針的原因是根據這個問題的特點,存水的高度取決於兩邊較短的那個內壁的高度。
使用指針對撞的方式不會錯過最優解。
經驗:雙指針、滑動窗口的問題,一般先從暴力枚舉開始思考,然後更改枚舉的順序,以達到剪枝加快計算的效果。
可以參考 盛最多水的容器(雙指針法,易懂解析,圖解),寫題解的同學 @Krahets 非常用心,且很熱心解答朋友的疑問。我寫題解的結構也參考了他的思路,希望對大家有幫助。