码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-11 Container With Most Water

时间:2015-03-09 22:09:40      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

思路:

假设有(i,A[i]),(j,A[j])构成的容器是目前发现的最大容器S;

则i的左边一定不存在k<i && A[k]>=A[i],否则与“目前发现的最大容器”这一假设矛盾;

同理,j的右边也不存在比A[j]大的线;

那么,可能的更大的容器在位于i,j之间。

取A[i]和A[j]较小的那个往中间移动(此时小的那个是瓶颈),

  1. 如果i<k<j && A[K] <= A[i],继续移动;

  2. 如果i<k<j && A[K] > A[i],则可能出现更大值,此时计算当前的面积S1

  3. 如果S1 > S,更新S1

  4. 在(i~k)或者(k~j)之间重复执行1-4步,直到i==j.

代码如下:

public int maxArea(int[] height) {
        if(height == null || height.length < 2)
            return 0;
        
        int left = 0;
        int currentLeft = height[left];
        int right = height.length - 1;
        int currentRight = height[right];
        int result = 0;
        while(left < right) {
            int tmp = Math.min(height[left], height[right]) * (right - left);
            if(tmp > result) {
                result = tmp;
            } 
            currentLeft = height[left];
            currentRight = height[right];
            
            if(height[left] <= height[right]) {
                while(left < right && height[left] <= currentLeft) {
                    left++;
                }
            } else {
                while(left < right && height[right] <= currentRight) {
                    right--;
                }
            }
        }
        return result;
    }

更加详细的分析:http://www.tuicool.com/articles/v6Fryij

LeetCode-11 Container With Most Water

标签:

原文地址:http://www.cnblogs.com/linxiong/p/4324538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!