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


    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;
        }
    }
    
  • 相关阅读:
    SSH-框架工作笔记
    Ajax基础
    Hibernate基础
    Struts1 中的国际化
    MyEclipse中的快捷键
    Oracle_存储过程
    oracle_开发子程序和包
    常用的正则表达式
    jQuery中的事件
    AcWing 1118. 分成互质组
  • 原文地址:https://www.cnblogs.com/yjxyy/p/10744587.html
Copyright © 2020-2023  润新知