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 }
  • 相关阅读:
    .NET泛型中的协变与逆变
    使用 Roslyn引擎动态编译代码
    Windows 自动更新服务恢复
    She Left Her Shoes
    .NET Core 配置
    EFCore中SQLSERVER 2008 的分页问题
    SQL SERVER 2012/ 2014 分页,用 OFFSET,FETCH NEXT改写ROW_NUMBER的用法(转)
    TFS命令行操作
    负载均衡(Load Balancing)学习笔记(三)
    负载均衡(Load Balancing)学习笔记(二)
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3779783.html
Copyright © 2011-2022 走看看