leetcode:Container With Most Water,leetcodecontainer

來源:互聯網
上載者:User

leetcode:Container With Most Water,leetcodecontainer

    給定一系列整數代表在0,1,2,3...座標點板的高度,求出在任意兩個板之間能裝水的最大截面積.

  1. 分析

       首先,我們會想到遍曆下每一個板,選取任意兩個板,求出最大的,但是這個會逾時,效率太低

      

 其次,我們樂意想到在遍曆的基礎上最佳化,即有一個預測,這樣可以在一定程度上提高效率,但是並不是太好,我試了下還


是不能過.

    

 我們就要想,能不能遍曆一遍就求出來.

    

    1:left = 0, right =height.size();

    

    2:如果left< right,則3,否則四

   

   3:求出此時面積的大小,並判斷左邊和右邊板的高度哪一個大,左邊小於右邊的話,left++;否則,right--;並判斷是否  

將Maxarea更新,返回2

   

   4:結束,返回最大面積


  窮舉

class Solution {public:    int maxArea(vector<int> &height) {        int area,Maxarea,high;        Maxarea = 0;        for(int i=0;i<height.size();i++){        if(height[i]==0) continue;        for(int j=0;j<i;j++){        area = (i-j)*(high=height[i]>height[j]? height[j]:height[i]);        if(area>Maxarea)        Maxarea = area;        }        }        return Maxarea;    }};
  預測最佳化

class Solution {public:    int maxArea(vector<int> &height) {        int area,Maxarea,high;        Maxarea = 0;        for(int i=0;i<height.size();i++){        if(height[i]==0) continue;        int steplen = i - Maxarea/height[i];        for(int j=0;j<i&&j<=steplen;j++){        area = (i-j)*(high=height[i]>height[j]? height[j]:height[i]);        if(area>Maxarea)        Maxarea = area;        }        }        return Maxarea;    }};

   雙指標

class Solution {public:    int maxArea(vector<int> &height) {        int left = 0;        int right = height.size() - 1;        int area,Maxarea,high,step;        Maxarea = 0;        int flag;        while(left<right){        area = (right-left)*(high=height[left]>height[right]? height[right]:height[left]);        if(height[left]<height[right])        left++;        else            right--;                if(area>Maxarea)        Maxarea = area;        }        return Maxarea;    }};



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.