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

[LeetCode]Container With Most Water

时间:2015-04-21 22:41:35      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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.

题意:假设有一个x,y的二维坐标,我们定义area(i,j) = min(xi,xj) * |i - j, 找出最大的area。
思路:用两个指针l,r分别指向数组两边,然后计算当前area,接着比较xl,xr大小,小的那个的下标变化。知道l>=r|。 这是由于当前的矩形宽度是最大的,那么接下来的矩形想想面积比当前的面积大,就只能够增加矩形的高。算法复杂度为O(N)
代码:

    public int maxArea(int[] height) {//O(N)
        int max = 0;
        int curr  = 0;
        int l = 0, r = height.length - 1;
        while (l < r){
            curr = Math.min(height[l],height[r]) * (r - l);
            max = Math.max(max, curr);
            if(height[l] < height[r]){
                l ++;
            }else if(height[l] > height[r]){
                r  --;
            }else {
                l ++;
                r  --;
            }
        }
        return max;
    }


[LeetCode]Container With Most Water

标签:leetcode

原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/45176327

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