leetcode 11. 盛最多水的容器
首先最好想的,肯定就是暴力解法,但是太慢了。
class Solution {
public int maxArea(int[] height) {
int max = 0;
for (int i = 0; i < height.length; i++) {
for (int j = i + 1; j < height.length; j++) {
int vol = calVol(height, i, j);
max = Math.max(max, vol);
}
}
return max;
}
public int calVol(int[] height, int i, int j) {
int w = j - i;
int h = Math.min(height[i], height[j]);
return w * h;
}
}
双指针法
两个指针分别指向数组的两端,然后不断移动短的那一个。
public class Solution {
public int maxArea(int[] height) {
int l = 0, r = height.length - 1;
int ans = 0;
while (l < r) {
int area = Math.min(height[l], height[r]) * (r - l);
ans = Math.max(ans, area);
if (height[l] <= height[r]) {
++l;
}
else {
--r;
}
}
return ans;
}
}