您的位置:首页 > 大数据 > 人工智能

【leetcode】Array——Container With Most Water(11)

2016-03-21 21:07 465 查看
题目:Given n non-negative
integers a1, a2,
..., an,
where each represents a point at coordinate (i, ai). n vertical
lines are drawn such that the two endpoints of line i is
at (i, ai)
and (i,
0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

思路:本以为和之前的题目:Largest Rectangle in Histogram解题思路一样,细想也不是。参考了leetcode的解法:https://leetcode.com/discuss/59635/easy-concise-java-o-n-solution-with-proof-and-explanation也许这个解法不好理解,还可以看看这个:https://leetcode.com/discuss/11482/yet-another-way-to-see-what-happens-in-the-o-n-algorithm

总结一下思路:

两个指针:left=0 right=height.length-1 。假如left=0,right=6:

如果height[left]<height[right],则0-5 0-4 … 0-1 都要比0-6小(准确来说是不可能比0-6大),所以left++。

如果height[left]>height[right],则1-6 2-6 … 5-6 都要比0-6小(准确来说是不可能比0-6大),所以right--

代码:

public int maxArea(int[] height) {
int left=0,right=height.length-1;
int max=0;
while(left<right){
max = Math.max(max, Math.min(height[left], height[right])*(right-left));
if(height[left]<height[right])
left++;
else
right--;
}

return max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: