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 }
  • 相关阅读:
    内部类与外部类的调用
    Docker学习(十二)中遇到的一些问题汇总
    Docker学习(十一)Docker系列结束-新的开始K8S
    Docker学习(十)Docker容器编排 Docker-compose
    Docker学习(九)Volumn容器间共享数据
    Docker学习(八)容器间单向通信
    Docker学习(七)实战
    Docker学习(六)Dockerfile构建自定义镜像
    Docker学习(五) Dockerfile基础命令
    Docker学习(四)Docker搭建Tomcat
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3779783.html
Copyright © 2011-2022 走看看