Day 6 刷题
我的思路:利用两层循环,暴力搜索所有组合的面积,找出最大值。
import java.util.*;
class Solution {
public int maxArea(int[] height) {
// 找height和间距
int maxArea = 0, iArea;
for (int p1 = 0; p1< height.length-1; p1++){
int p2 = p1 + 1;
iArea = Math.min(height[p1],height[p2]);
// 当新容器面积更大或是指针超出范围
while (p2 < height.length){
iArea = (p2-p1)*Math.min(height[p1],height[p2++]);
maxArea = maxArea>iArea?maxArea:iArea;
}
}
return maxArea;
}
}
Krahets优雅的做法:找短板,短板内移不会带来面积增大。
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;
}
}
标签:p2,p1,int,res,height,Leecode,maxArea
From: https://www.cnblogs.com/xytang-mini-juan/p/18085160