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 };
  • 相关阅读:
    洛谷 P3868 [TJOI2009]猜数字
    洛谷 P2661 信息传递
    hdu 5418 Victor and World
    洛谷 P5024 保卫王国
    洛谷 P2470 [SCOI2007]压缩
    双栈排序 2008年NOIP全国联赛提高组(二分图染色)
    理想的正方形 HAOI2007(二维RMQ)
    10.23NOIP模拟题
    疫情控制 2012年NOIP全国联赛提高组(二分答案+贪心)
    图论模板
  • 原文地址:https://www.cnblogs.com/huenchao/p/7651280.html
Copyright © 2011-2022 走看看