zoukankan      html  css  js  c++  java
  • 11. Container With Most Water

    11. Container With Most Water

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

     1 //这题我一开始理解错了,我以为全部能存下多少水,其实是找出哪2个挡板可以存下最多水,并返回水容量。下面代码是一开始理解错的。
     2 
     3 /**
     4  * @param {number[]} height
     5  * @return {number}
     6  */
     7 var maxArea = function(height) {
     8     
     9     var len = height.length;
    10     
    11     var left = 0,max = 0,right = len - 1,total = 0;
    12     
    13     while(left < right){
    14         
    15         //比如 左边高度是 11  右边高度是 9, 根据短板原理,肯定 面积 = 9*底;
    16         
    17         //双指针的解法
    18         
    19         var min = Math.min(height[left],height[right]);
    20         
    21          if(min > max){
    22              
    23              total += (min-max) * (right - left);
    24              
    25              max = min;
    26              
    27          }
    28         
    29            height[left] > height[right] ? right-- : left++;
    30     }
    31     
    32     return total;
    33 };
     1 //正确代码
     2 /**
     3  * @param {number[]} height
     4  * @return {number}
     5  */
     6 var maxArea = function(height) {
     7     
     8     var len = height.length;
     9     
    10     var left = 0,max = 0,right = len - 1;
    11     
    12     while(left < right){
    13         
    14         //比如 左边高度是 11  右边高度是 9, 根据短板原理,肯定 面积 = 9*底;
    15         
    16         //双指针的解法
    17         
    18          max = Math.max(max,Math.min(height[left],height[right]) * (right - left));
    19         
    20     
    21          height[left] > height[right] ? right-- : left++;
    22     }
    23     
    24     return max;
    25 };
  • 相关阅读:
    07 总结ProgressDialog 异步任务
    1. vim 的安装及配置
    debian 源设置 ( apt-get 不能安装)
    在Debian中安装VNC Server
    让BB-Black通过usb0上网
    常用的一些 linux 指令
    Linux下同一目录内文件和目录为什么不能同名?
    beaglebone black 与电脑互传文件(夹)
    永久修改 putty字体大小
    Beaglebone Black的引脚分配
  • 原文地址:https://www.cnblogs.com/huenchao/p/7651280.html
Copyright © 2011-2022 走看看