zoukankan      html  css  js  c++  java
  • Leetcode: Container With Most Water

    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.

    这道题我考虑过类似Trapping most water的做法,不大一样。那道题寻找左右最大元素,我可以确定那就是最优解,但是在这里,即使寻到了左右最大元素,我也不敢确定那是最优解。 然后我有考虑了DP全局最优&局部最优的做法,发现局部最优的递推式很难写。所以没有法了,网上看到说这道题用夹逼方法

    The most strait forward approach is calculating all the possible areas and keep the max one as the result.  This approach needs O(n*n) time complexity, which could not pass OJ (Time limit exceed).

    There is so called "closing into the centre" approach.  Idea of which is set two pointer at the start and end of the array (which I has thought about that), then move the shorter pointer each iteration.  The idea be hide this movement is that if we move the longer line, no matter how many steps we move, the new area would be smaller than the one before movement.  This is because area = (end-start)*min(height[start], height[end]) <- after move, (end-start) decrease, min(height[start], height[end]) remains no change, still the "shorter line".

     网上看了一下比较好的解决方法,也是所谓的夹逼算法

     1 public int maxArea(int[] height) {
     2     if(height==null || height.length==0)
     3         return 0;
     4     int l = 0;
     5     int r = height.length-1;
     6     int maxArea = 0;
     7     while(l<r)
     8     {
     9         maxArea = Math.max(maxArea, Math.min(height[l],height[r])*(r-l));
    10         if(height[l]<height[r])
    11             l++;
    12         else
    13             r--;
    14     }
    15     return maxArea;
    16 }
  • 相关阅读:
    jQuery.getJSON的缓存问题的解决办法
    MFC Tab Control控件的详细使用
    JavaScript 闭包深入理解(closure)
    STL中sort函数用法简介
    STL中qsort的七种用法
    学习Javascript闭包(Closure)
    使用 Visual Studio 分析器找出应用程序瓶颈
    各种语言性能测试工具一览表
    Javascript 链式作用域
    MessageBox、::MessageBox 、AfxMessageBox三者的区别 .
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3779783.html
Copyright © 2011-2022 走看看