题目描述:算法
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.spa
给定n个非负整数a1,a2,...,an,其中每一个表明坐标(i,ai)处的一个点。 绘制n条垂直线,使得线i的两个端点处于(i,ai)和(i,0)处。 找到两条线,它们与x轴一块儿造成一个容器,以使容器包含最多的水。
注意:您不得倾斜容器。指针
/* * 贪心算法:从两边开始向中间缩小;每一步比较左右边界高度,高度小的那个向里走一步 * * 这个贪心算法,为何最优解不会被错过? 反证法 假设会被错过。 * 假设最优解是横坐标为x1,x2(x2在右边)的这两个点组成的 * 只考虑扫描到x2时,x1被错过的状况(x2被错过同理): * 被错过指的是 当右指针向左扫描通过x2以后,左指针还在x1的左边P处时,x1被错过。 * * 状况一 x2>p: x2会被保留,而后左指针向右移动到x1,x1不会被错过 * 状况二 x2<p: 小状况一:height[p]>height[x1] 则最优解为 p,x2而不是 x1,x2。 假设不成立 * 小状况二:p<=x1 最优解仍是p,x2。 假设不成立 * //由于x2比p和x1都小,因此容器高度取决于x2,而p比x1偏左,因此p,x2比x1,x2面积大 * * */ public int maxArea(int[] height) { if(height.length<=2) return 0; int left=0,right=height.length-1; int maxArea=0; while(left<right) { int area = Math.min(height[left],height[right])*(right-left); maxArea = Math.max(maxArea, area); if(height[left]<=height[right]) { left++; }else { right--; } } return maxArea; }