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++; else j--; } 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; }
Container With Most Water--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44903321