leetcode 盛最多水的容器
leetcode 盛最多水的容器

暴力遍历法
i 指向第 1 块板子,j 指向第 2 块板子,计算面积,j 指向第 3 块板子,计算面积,j 指向第 4 块板子,计算面积.............., 可得出 i 指向第 1 块时,最多盛水量。
i 指向第 1 + 1块板子,j 指向第 3 块板子,计算面积,j 指向第 4 块板子,计算面积,j 指向第 5 块板子,计算面积.............., 可得出 i 指向第 1 + 1块时,最多盛水量。 . . .
最后可得出 i 指向第 1 ,2,3...n 块板子时,最多盛水量。求最大值即可
class Solution {
public int maxArea(int[] height) {
int s_max = 0;
for (int i = 0; i < height.length - 1; i ++) {
for (int j = i + 1; j < height.length; j ++) {
int s = (j - i) * Math.min(height[i], height[j]);
s_max = Math.max(s, s_max);
}
}
return s_max;
}
}
缺点也是显而易见,竟然接近 1s ...
双指针
向中间收紧法 i 指向第一块板子,j 指向最后一块板子,计算面积, 当 i 指向的板子高度 < j 指向的板子高度 时, i ++ 否则 j -- 直到 i j 相遇
public int maxArea(int[] height) {
int res = 0;
int i = 0;
int j = height.length - 1;
while (i < j) {
int area = (j - i) * Math.min(height[i], height[j]);
res = Math.max(res, area);
if (height[i] < height[j]) {
i++;
} else {
j--;
}
}
return res;
}
作者:nettee
链接:https://leetcode-cn.com/problems/container-with-most-water/solution/on-shuang-zhi-zhen-jie-fa-li-jie-zheng-que-xing-tu/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

我觉的上面的方法还可以再优化 i++, j-- 后在加一层判断 移动后的柱子高度 <= 移动前的柱子高度 继续 移动
public int maxArea(int[] height) {
int res = 0;
int i = 0;
int j = height.length - 1;
while (i < j) {
res = Math.max(res, (j - i) * Math.min(height[i], height[j]));
if(height[i] < height[j]) {
int tempi = height[i];
do{
i++;
}while(height[i] <= tempi && i < j);
}else{
int tempj = height[j];
do{
j--;
}while(height[j] <= tempj && i < j);
}
}
return res;
}

最后放一个 (有点意思)
class Solution {
public int maxArea(int[] height) {
int i = 0, j = height.length - 1, res = 0;
while(i < j){
res = height[i] < height[j] ?
Math.max(res, (j - i) * height[i++]):
Math.max(res, (j - i) * height[j--]);
}
return res;
}
}
作者:jyd
链接:https://leetcode-cn.com/problems/container-with-most-water/solution/container-with-most-water-shuang-zhi-zhen-fa-yi-do/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。