leetcode------Container With Most Water

标题: Container With Most Water
通过率: 31.9%
难度: 中等

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.

Note: You may not slant the container.

本题就是找一个最大面积的长方形,公式就是 min(h(l),h(r))*(r-l)

那么肯定是从两头往里面找,如:

若h(l)<h(r)时就从头开始找到一个比h(l)大的,然后计算一次,

反之则从后面找到一个比h(r)大的再计算一次,

每次计算都要更新一次result,最后的result一定是最大的

代码如下:

 1 public class Solution {
 2     public int maxArea(int[] height) {
 3         int l=0,r=height.length-1,result=0;
 4         while(l<r){
 5             result=Math.max(result,Math.min(height[l],height[r])*(r-l));
 6             if(height[l]<height[r]){
 7                 int k=l;
 8                 while(k<r&&height[k]<=height[l]){
 9                     k++;
10                 }
11                 l=k;
12             }
13             else{
14                 int k=r;
15                 while(k>l&&height[k]<=height[r]){
16                     k--;
17                 }
18                 r=k;
19             }
20         }
21         return result;
22     }
23 }

 

posted @ 2015-03-06 11:11  pku_smile  阅读(133)  评论(0编辑  收藏  举报