zoukankan      html  css  js  c++  java
  • leetcode 11. Container With Most Water

    first, i use exhausitive search. however, it will exceed the time limit.

    int maxArea(vector<int>& height) {
            int n=height.size();
            int max=0;
            int s;
            for(int i=0;i<n;i++)
                for(int j=i+1;j<n;j++)
                {
                    //cout<< i<<endl;
                    //cout<<j<<endl;
                    //cout<<n<<endl;
                    int a=min(height[i],height[j]);
                    cout<<a<<endl;
                    s=(j-i)*a;
                    if(s>max)
                        max=s;
                }
            return max;
        }

    the time speed is O(n^2)

    then, i change the strategy. for impove the speed, I will search the vector from two direction. From the left to right and from right to left, until all the numbers has been checked.

    int maxArea(vector<int> & height)
        {
            int n=height.size();
            int max=0;
            int s;
            for(int i=0,j=n-1;i<j;)
            {
               s=(j-i)*min(height[i],height[j]);
                cout<< i<<endl;
                cout<<j<<endl;
                if(s>max)
                    max=s;
                if(height[i]>height[j])
                    j--;
                else
                    i++;
            }
            return max;
        }

    the intuition behind this approach is that we want to find the biggest two line to construct the container. because the area is decided by the shorter line.  To maximize the area, we need to consider the area between the lines of larger lengths. if we try to move the pointer at the longer line inwards, we won't gain any increase in area, since it is limited by the short line.O(n)

    if left > right, it means that we should find a biger left.

    if left <right, it means that we should find a biger left.

  • 相关阅读:
    华为2019软件题
    图像的存储格式转化(python实现)
    windows+两个ubuntu系统的引导启动问题
    《视觉SLAM十四讲》课后习题—ch6
    视觉SLAM十四讲课后习题—ch8
    LINQ根据时间排序问题(OrderBy、OrderByDescending)
    Element的扩展
    CSharp
    jQuery函数使用记录
    日记越累
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7202034.html
Copyright © 2011-2022 走看看