LeetCode #11 - Container With Most Water

题目描述:

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


这道题如果用两层循环,依次遍历显然效率太低,考虑下面的事实可以让遍历简单很多:

假设当前最优解为(i, ai),(j, aj),那么可以初始化i=1,j=n,从坐标两端开始搜索,根据s=(j-i)*min(ai,aj),不断更新最优解,必定能找到最优解。

这是因为i和j的移动是由ai和aj来判断的,必须让高度较小的一方移动,当ai<aj时,ai与aj-1、aj-2、aj-3......的组合不必考虑,因为高度不变,长度减小。所以每次移动即相当于舍弃了(j-i-1)种组合,只需要考虑每次移动后的这一种组合是否为最优解即可。由i=1,j=n到i=j需要n-1次移动,依次舍弃不需要考虑的(n-2)、(n-3)、(n-4).....2、1种组合,真正可能存在最优解的只有(n-1)次移动产生的(n-1)种组合,所以总组合数为(n-1)+(n-2)+(n-3)+(n-4).....+2+1=C(n,2),这正是i和j所有可能的组合数。

可见此方法在保证不遗漏的情况下,只考虑了(n-1)种组合而舍弃了其余的不可能存在最优解的组合,大大降低了时间复杂度。


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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值