题解 | #盛水最多的容器#
盛水最多的容器
https://www.nowcoder.com/practice/3d8d6a8e516e4633a2244d2934e5aa47
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param height int整型一维数组
* @return int整型
*/
public int maxArea (int[] height) {
// write code here
//输出结果为面积,跟起点和终点有关,等于两个高度的最小值乘以索引差值
//初始化结果
int res = 0;
// 数组长度小于2,直接输出0
if(height.length < 2){
return res;
}
// 初始化左指针和右指针的值
int left = 0 , right = height.length -1;
while(left < right){
res = Math.max(res,(right - left)* Math.min(height[left],height[right]));
if(height[right] > height[left]){
left++;
}else{
right--;
}
}
return res;
}
}
首先确定面积公式:左右端点距离*短边长度,虽然题目说任选两个边,其实按照左右指针遍历,就能找到
一开始,初始化左右指针,然后对比两个边的长度,反正都是要缩小宽度的,肯定往较短边方向缩小,这样不会漏掉比当前值还大的面积。这一点很重要。
嘉士伯公司氛围 389人发布