Container With Most Water

来源:互联网 发布:大数据技术是什么 编辑:程序博客网 时间:2024/06/05 23:45
<pre name="code" class="java">
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.Note: You may not slant the container.

z首先题目的意思是

以数组的点height[index]为y轴坐标,数组的位置index为x轴坐标。连接(index,0)与(index,height[index])两点形成一条直线。

在所有的直线中找出两条直线,使这两条直线与x轴围成个|_|的形状容器,求所有容器中最大面积。


这道题想了很久都没想到答案。后来看别人的答案才自己写出来的。


问题的解法是双指针。双指针在前面的3sum问题中也用到过。自己概括地说,双指针能够把你O(n^2)降为O(n)。就是通过比较头尾两个指针,然后来移动其中一个就行了。


这道题也是这样的解法。

首先两个指针一头start,一尾end。可以求得最大面积。

如果height[start]>height[end],那么需要end-=1;因为面积是取决于最小的那一条边,因此我们希望通过移动end能够获得更大的边,并且来比较是否会超过当前的最大值。

相反,如果height[start]<=height[end];then start+=1;

maxresult=maxresult>Math.min(height[start],heigth[end])*(end-height)?maxresult:Math.min(height[start],heigth[end])*(end-height)

所以代码如下。本文就是要理解双指针的妙处。

public class Container_With_Most_Water {public int maxArea(int[] height) {        int maxresult=-1;        int start=0,end=height.length-1;        while(start<end){        if(height[start]>height[end]){        maxresult=maxresult>height[end]*(end-start)?maxresult:height[end]*(end-start);        end--;        }        else{        maxresult=maxresult>height[start]*(end-start)?maxresult:height[start]*(end-start);        start++;        }        }        return maxresult;    }/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub}}


0 0