首页 > 其他 > 详细

22.Container With Most Water(能装最多水的容器)

时间:2019-04-21 12:35:04      阅读:157      评论:0      收藏:0      [点我收藏+]

Level:

??Medium

题目描述:

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 and n is at least 2.

技术分享图片

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

思路分析:

??从两端往中间搜索,面积的计算方法为两端中较小的作为高,坐标差作为宽,然后求积就是面积,时间复杂度为O(n)。

代码:

public class Solution{
    public int maxArea(int []height){
        int i=0; //左端
        int j=height.length-1;
        int maxarea=Math.min(height[i],height[j])*(j-i);
        while(i<j-1){
            if(height[i]<=height[j])
                i++;             //为什么要i++而不是j++,因为要尽可能保留高度高的
            else
                j--;
            int area=Math.min(height[i],height[j])*(j-i);
            maxarea=Math.max(maxarea,area);
        }
        return maxarea;
    }
}

22.Container With Most Water(能装最多水的容器)

原文:https://www.cnblogs.com/yjxyy/p/10744587.html

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