Container With Most Water--LeetCode

来源:互联网 发布:七彩网络下载 编辑:程序博客网 时间:2024/06/01 10:36

题目:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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;}

ps:当然也可以使用另一种思考方式,从前两个开始往后增加,当往后增加导致总数减少时,前面的增加。当前面的增加导致减少时,后面的增加。这里的增加是指针右移
1 0
原创粉丝点击