Container With Most Water

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 linei 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.

题的意思也很好理解。容量=min(ai, aj)*(j-i)。

1)O(N^2)的算法

class Solution {
public:	
    int maxArea(vector& height) {        
	//	int i=0, j=0;
		int maxV=0;	
		for(int i=0; i maxV) {
					maxV = Vol;
				}
			}
		}
		return maxV;
    }
};

2)O(N):如果最值点取在ai,aj,则aj的右侧不会有比aj更高的点。若有的话,设为ak,则min(ai,ak)*(k-i)比min(ai,aj)*(j-i)大,矛盾。同理ai的左侧也不会有比ai高的点。所以若我们已经得到两个候选点ai和aj,比候选更优的点只能在(i,j)范围内且其高度高于ai和aj。所以可以从两侧向内遍历,但是要注意的是每一个循环中哪一侧往内缩进,从上述推理可以得出要缩进的是ai和aj中的较低者。比如ai=2,aj=3时,i要执行i++,因为ai和(i, j)内的所有的点组成的面积都要小于和aj的。

class Solution{
public:
	int maxArea(vector &height) {
		int left=height[0], right=height[height.size()-1];
		int i=0, j=height.size()-1;
		int maxV=min(height[i], height[j])*(j-i);
		while(i left || height[j] > right) {
				int tempV=min(height[i], height[j])*(j-i);
				if(tempV > maxV) {
					maxV = tempV;
					left=i;
					right=j;
				}				
			}
			if(height[i] <= height[j])
				++i;
			else 
				--j;
		}
		cout<


你可能感兴趣的:(LeetCode算法)