11. Container With Most Water

来源:互联网 发布:远盾网络 编辑:程序博客网 时间:2024/05/16 09:43

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.

题意:给定n条竖直的线段,从中选出两条使其与x轴组成容器,使容器的面积最大。

思路:1. 假定选定的两条线为C(i, j),则j之后一定没有线比aj更高,同样i之前一定没有线比ai更高。  2. 假定目前已有一个较佳的区间[x, y],那么问题的求解就限定在区间[x, y]内的那些(ai>=ax, aj>=ay)的线上。可以逐步缩减空间。  3. 在空间逐步缩减时要注意:每次从ai,aj两条线中的较小的线开始移动到下一待选位置。因为高的那条线迟早还要和其他线组成待测容器, 较矮的那条线则不用继续测了。算法的时间复杂度为O(n)。

class Solution {public:int maxArea(vector<int>& height) {int size = height.size();if (size < 2)return 0;int area = 0;int i = 0, j = size - 1;while (i < j){int tmp;if (height[i] < height[j]){int  a = height[i];tmp = a *(j - i);i++;while (i < j && height[i] <= a)i++;}else{int  a = height[j];tmp = a *(j - i);j--;while (j>i && height[j] <= a)j--;} if (tmp > area)area = tmp;}return area;}};



          

0 0
原创粉丝点击