zoukankan      html  css  js  c++  java
  • container-with-most-water

    /**
    * @author gentleKay
    * 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.
    *
    * 给定n个非负整数a1,a2,…,an,其中每个表示一个坐标点(i,ai)。
    * 画n条垂直线, {使线i的两个端点位于(i,ai)和(i,0)。(这句话可以不用看)}
    * 找到两条线,与x轴一起构成一个容器,这样容器中的水就最多了。
    * 注意:不要使容器倾斜。
    */

    我个人觉得题目讲的不是很清楚,我查了一下,找到一张图。

    这张图一看就很明了,让我们求得是,两条线之间的面积最大。

    输入: [1,8,6,2,5,4,8,3,7]
    输出: 49

    图片的来源:https://blog.csdn.net/weixin_39364289/article/details/89146527

    /**
     * @author gentleKay
     * 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.
     * 
     * 给定n个非负整数a1,a2,…,an,其中每个表示一个坐标点(i,ai)。
     * 画n条垂直线, {使线i的两个端点位于(i,ai)和(i,0)。(这句话可以不用看)}
     * 找到两条线,与x轴一起构成一个容器,这样容器中的水就最多了。
     * 注意:不要使容器倾斜。
     */
    
    public class Main08 {
    
    	public static void main(String[] args) {
    		int[] height = {1,1};
    		System.out.println(Main08.maxArea(height));
    	}
    	
    	public static int maxArea(int[] height) {
    		int start = 0;
    		int end = height.length-1;
    		int max = 0; int area = 0;
    		while (start < end) {
    			if (height[start] < height[end]) {
    				area = (end - start) * height[start];
    				start++;
    			}else {
    				area = (end - start) * height[end];
    				end--;
    			}
    			if (area > max) {
    				max = area;
    			}
    		}
            return max;
        }
    }
    

      

  • 相关阅读:
    第八章 数据库连接JDBC(待续)
    Linux下chkconfig命令详解
    在Debian上用Bind 配置DNS服务器
    【故障处理】mysql出现大量slave bin日志,将磁盘空间占满
    Debian 配置apt-get源
    Debian Vi 简介
    SaltStack之Master配置文件详解
    AUTOSSH,ssh反向代理
    yum简单安装salt master与minion
    salt安装与简单使用---基于centos6.5
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11238121.html
Copyright © 2011-2022 走看看