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 };
  • 相关阅读:
    Zabbix通过进程名监控进程状态配置详解
    kibana 统计field所有值百分比
    使用Logstash filter grok过滤日志文件
    python 修改文件内容
    清理elasticsearch的索引
    zabbix3.2.1安装graphtrees插件
    snmpwalk用法
    Zabbix通过SNMPv2监控DELL服务器的硬件信息
    zabbix上的宏(macro)介绍
    解决TeamViewer无法按给定网络地址联系伙伴
  • 原文地址:https://www.cnblogs.com/huenchao/p/7651280.html
Copyright © 2011-2022 走看看