题解 | #盛水最多的容器#
盛水最多的容器
https://www.nowcoder.com/practice/3d8d6a8e516e4633a2244d2934e5aa47
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param height int整型一维数组
* @param heightLen int height数组长度
* @return int整型
*/
int getmin(int a,int b){
return a>=b? b:a;
}
int getmax(int a,int b){
return a>=b? a:b;
}
int maxArea(int* height, int heightLen ) {
// write code here
int i = 0, j = heightLen-1;
int max = 0, tmp = 0;
if (heightLen < 2)
return 0;
/*
//另一种解题思路,两两相乘,n*(n-1)个结果中取最大
for(i=0;i<heightLen-1;i++){
for(j=i+1;j<heightLen;j++){
if(height[i]<height[j]){
tmp=(j-i)*height[i];
max=max>tmp?max:tmp;
}
else{
tmp=(j-i)*height[j];
max=max>tmp?max:tmp;
}
}
}*/
while (i != j) {
// j-i:表示宽度(x轴两点之间距离)
// 选取 i,j各点y轴高度最小
//两者乘机为盛水多少
max = getmax(max, getmin(height[i], height[j]) * (j - i));
//从两端往中间缩小,哪端矮往中间缩
height[i] >= height[j] ? j-- : i++;
}
return max;
}

查看3道真题和解析