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;}