一、题目还原
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
示例:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
二、解题思路
Solution 1:暴力循环法
① 两层循环逐一计算组成面积大小,取最大值返回
Solution 2:中心靠近
① 以横坐标最左侧left和最右侧right为起始点计算面积
② 如果左侧的高度低,则向右移动left++,反之左移right–
③ 返回最大面积
三、代码展示
① main函数
public static void main(String[] args) {
int[] height = {1,8,6,2,5,4,8,3,7};
System.out.println("maxArea == "+maxArea(height));
System.out.println("maxArea2 == "+maxArea2(height));
}
② 暴力法方法函数
//暴力法
public static int maxArea(int[] height) {
if(height.length < 2){
return 0;
}
int result = 0;
Map<Integer,Integer> map = new HashMap<Integer, Integer>();
for(int i = 0 ; i < height.length ; i ++){
for(int j = i+1 ; j < height.length ; j ++) {
result = Math.max(result,(j - i) * Math.min(height[i],height[j]));
}
}
return result;
}
控制台输出:
maxArea == 49
Process finished with exit code 0
② 中心靠近方法函数
//中心靠近
public static int maxArea2(int[] height) {
//EdgeCase
if(height.length < 2){
return 0;
}
int left = 0;
int right = height.length - 1;
int result = 0;
while(left < right){
result = Math.max(result,(right - left) * Math.min(height[right],height[left]));
if(height[left] < height[right]){
left ++;
}else{
right --;
}
}
return result;
}
控制台输出:
maxArea2 == 49
Process finished with exit code 0
四、自我总结
LeetCode第十一题,难度为中等。做了前十题之后,博主发现本题和之前做过的题目都很类似,虽然应用场景不一样,但是所使用的算法逻辑倒是十分相近。这道题和判断回文字符的思想就非常接近,在那道题当中使用的是中心扩散,这道题使用的中心靠近。
- 博主最近也将刷题的代码上传到github中,欢迎各位大佬们指点一二
Github仓库地址:https://github.com/w735937076/LeetCode