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.

  • 相关阅读:
    如何提高工作效率,重复利用时间
    好记性不如烂笔头
    如何应对面试中关于“测试框架”的问题
    通宵修复BUG的思考
    工作方法的思考
    别认为那是一件简单的事情
    开发人员需要熟悉缺陷管理办法
    不了解系统功能的思考
    如何布置任务
    事事有回音
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7202034.html
Copyright © 2011-2022 走看看