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

来源:互联网 发布:数据与标志的关系 编辑:程序博客网 时间:2024/06/06 07:26

题目:Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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;}


0 0
原创粉丝点击