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.

  • 相关阅读:
    java类研究(String)
    webservices
    LoadRunner(软件性能测试工具)
    java线程
    lucene solr
    java IO
    实现一个可变长数组
    [北大程序设计与算法]--虚函数与多态的实例
    A1155 Heap Paths [堆的dfs]
    A1154 Vertex Coloring
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7202034.html
Copyright © 2011-2022 走看看