题解 | #盛水最多的容器#
盛水最多的容器
http://www.nowcoder.com/practice/3d8d6a8e516e4633a2244d2934e5aa47
解题思路:
利用双指针的思想,在数组的左右各设置一个指针向中间移动,但为了节省运算时间,在移动时height值较高的那边优先。每次移动更新一次最大值。
代码展示:
import java.util.*;
public class Solution {
public int maxArea (int[] height) {
// write code here
//先排除特殊情况
if (height.length < 2)
return 0;
int volume = 0;
//设置两个指针
int left = 0, right = height.length - 1;
while (left != right) {
//更新volume
volume = Math.max((right - left) * Math.min(height[left], height[right]), volume);
//height值较低指针优先移动
if (height[left] < height[right])
left++;
else
right--;
}
return volume;
}
}
查看27道真题和解析