• 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 }
  • 相关阅读:
    使用dozermapper,处理不了LocalDateTime的映射问题:java.lang.NoSuchMethodException: java.time.LocalDateTime.<init>()
    mybatis-plus使用Wrapper自定义sql时出现错误:Invalid bound statement (not found)
    com.baomidou.mybatisplus.core.mapper 不存在
    python爬虫
    DRF源码系列分析
    python学习目录
    脚本加载django环境
    celery定时任务
    用脚本创建django-orm数据库表数据
    关于python很吊的一项技术!!!!!
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3779783.html
Copyright © 2020-2023  润新知