Container With Most Water--LeetCode,leetcode

來源:互聯網
上載者:User

Container With Most Water--LeetCode,leetcode
題目:

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.

思路:如果採用最簡單的方法就是使用暴力搜尋,平方的時間複雜度,但是也可以使用簡單的方法

接下來我們考慮如何最佳化。思路有點類似於Two Sum中的第二種方法--夾逼。從數組兩端走起,每次迭代時判斷左pointer和右pointer指向的數字哪個大,如果左pointer小,意味著向左移動右pointer不可能使結果變得更好,因為瓶頸在左pointer,移動右pointer只會變小,所以這時候我們選擇左pointer右移。反之,則選擇右pointer左移。在這個過程中一直維護最大的那個容積。代碼如下:

#include <iostream>#include <vector>#include <string>#include <stack>using namespace std;/*能裝最多水*/ int area(vector<int> &height, int i, int j)  {      int h = height[i]<height[j]?height[i]:height[j];      return h*(j-i);  }  int maxArea(vector<int> &height) {      int max=0;      for(int i=0;i<height.size();i++)      {          for(int j=i+1;j<height.size();j++)          {              int a = area(height,i,j);              if(a>max)              max=a;          }      }      return max;  }  int maxarea(vector<int>& vec){int maxarea=0;int first,second;int i=0,j=vec.size()-1;while( i<j){if(min(vec[i],vec[j])*(j-i) > maxarea){maxarea = min(vec[i],vec[j])*(j-i);}if(vec[i] < vec[j])i++;elsej--;}return maxarea;}int main() {int array[]={4,3,4,5,7,9,7,6,8,5,3,2};vector<int> vec(array,array+sizeof(array)/sizeof(int));cout<<maxArea(vec)<<endl;cout<<maxarea(vec)<<endl;return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.