leetcode 11 - 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 thetwo endpoints of line i isat (iai) and (i,0). Find two lines, which together with x-axis forms a container, such that thecontainer contains the most water.

Note: You may not slant the container and n is at least 2.

分析:

其实就是找到最大的面积数。i就相当于坐标的X,Y就是高,面积就是X乘以Y。

在本题中,a[i] , a[j]表示yi和yj ,Y = min(yi,yj)。取桶最矮的一部分。

 j – i =X(j > i)桶底部的宽度。

面积就是X * Y = min(yi,yj) * j – i;

考虑到a的长度大小为n,不难看出最优的时间复杂度为O(n)

    int maxArea(vector<int>& height) {
    	
    	int max = 0;
    	int start = 0;
    	int end = height.size() - 1;
    	int temp = 0;
    	max = min(height[0],height[end]) * (end - start);
    	for( ; start < end ; start++){
    		while(height[start] > height[end] && start < end){
    			temp = min(height[start],height[end]) * (end - start);
    			if(max < temp)
    				max = temp;
    				end--;
			}
			temp = min(height[start],height[end]) * (end - start);
			if(max < temp)
				max = temp;
		}
    	
    	return max;
    	
    	
        
    }

)。

因此,可以从两边向中间遍历数组(个人比较喜欢两边向中间遍历,其他方法也可以),稍微利用一点对桶高的贪心思维。每次保留最长的Y,然后从另外一边遍历。比如

2 1 3 4 5 2 1 4

start表示开始的下标,end表示结束的下标

现在看到a[start]是2,a[end]是4,4 > 2 ,从左边遍历,start++。

然后一直走到5,5 > 4 ,然后从右边开始走,end--,到start不小于end就结束了。每次走到一个点的时候就计算面积的值,然后和历史最大面积比较,取较大值保存,算法结束后就得到最大面积的值。

 

最后,算法复杂度就是O(n)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值