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.
给定n个非负的整数a1, a2, ..., an,(i, ai) and (i, 0)分别表明坐标(i, ai)。链接(i, ai) and (i, 0)画直线,共有n条。找出两条直线,使得两条直线与x轴造成的容器可以盛最多的水。java
难度:Medium算法
若是容器盛水最多函数
矩形面积最大。
盛水量的多少,由两条垂线中较短的一条决定。
两条垂线中较短一条尽量长。spa
时间复杂度O(n^2)code
遍历orm
public int maxArea(int[] h) { int N=h.length; int max=0; for(int i=0;i<N-1;i++) for(int j=i+1;j<N;j++){ if(area(h,i,j)>max) max=area(h,i,j); } return max; } //i<j private int area(int[]h,int i,int j){ if(h[i]<h[j]) return (j-i)*h[i]; else return (j-i)*h[j]; }
当两个值作比较,选取两个之中较大或较小值时,可采用Math.min()/max()函数索引
private int area(int[]h,int i,int j){ return (j-i)*Math.min(h[i], h[j]); }
max=Math.max(area(h,i,j), max);
以序列最外面两条边造成的面基为起始面积,找出两条边中较小的一条,若是是左边的边索引+1,若是是右边的边索引-1。缘由是找出一条更大的边来代替较小的边,以使得整个容器最大。图片
public int maxArea(int[] h) { int N=h.length; int max=0; for(int i=0,j=N-1;i<j;){ max=Math.max(area(h,i,j), max); if(h[i]<h[j]) i++; else j--; } return max; } /* return the area between i and j * @param i<j */ private int area(int[]h,int i,int j){ return (j-i)*Math.min(h[i], h[j]); }