首页 > 其他 > 详细

LeetCode Container With Most Water

时间:2014-10-16 12:02:13      阅读:345      评论: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.

 

题意:二维坐标系里有 n 个点 (i, ai), ai >= 0,从 (i, ai)到(i, 0)划竖线,共有 n 条竖线。
找出两条竖线,使得它们构成的矩形的面积最大,矩形的高取决于最短的竖线。
思路:贪心
从首尾两个下标head 和trail 处开始扫描,用一个变量 maxArea 保持当前最大的矩形面积。
如果head 指向的竖线短于 trail 的,则右移 head
否则左移 trail
计算面积,更新 maxArea
复杂度:时间O(n),空间O(1)

 

public class Solution {
    public int maxArea(int[] height) {
        if (height.length<2) {
            return 0;
        }
        
        int leftEdge=0;
        int rightEdge=height.length-1;
        int maxarea=0,area=0;
        while (leftEdge!=rightEdge) {
                area=Math.min(height[leftEdge], height[rightEdge])*(rightEdge-leftEdge);
                if (area>maxarea) {
                    maxarea=area;
                }
                if (height[leftEdge]<height[rightEdge]) {
                    leftEdge++;
                }else {
                    rightEdge--;
                }
        }
        return maxarea;
    }
}

 

LeetCode Container With Most Water

原文:http://www.cnblogs.com/birdhack/p/4028278.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!