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 }
  • 相关阅读:
    SQL SERVER 2005中同义词实例
    内聚性是模块之所以成为模块的原因--一个中心、单一职责
    软件开发的方法论
    系统集成与软件开发
    编程的本质是构建---建构你想要表达的世界
    编程思想与以人为本-编程的本质
    软件开发之道-软件开发背后的哲学
    swift 协议(结合扩展)的特点
    swift的特性:扩展、协议、泛型
    从数据流角度管窥 Moya 的实现(一):构建请求
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3779783.html
Copyright © 2011-2022 走看看