Container With Most Water-LeetCode

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 and n is at least 2.

题目大意:一排数组保存了一排竹竿的高度,数组index的号码即竹竿编号和相对位置。要求的是两个竹竿所围成的最大面积=竹竿距离*最矮的那个竹竿高度。

题目解法有两种:

(1)两重for循环枚举所有可能的竹竿组合,计算可能的最大面积。然而这种方法必然超时,因为时间复杂度是O(n2)。即使代码中第二层循环的index是j从i+1处开始的,也会超时,也就是说LeetCode封死了想用两层循环解题的思路。然而还是给出反面的教材吧,见代码。

public class Solution {
    public int maxArea(int[] height) {
    	int maxarea=0;
        for(int i=0;i<height.length;i++){
        	for(int j=i+1;j<height.length;j++){
        		int area=(j-i)*(height[i]>height[j]?height[j]:height[i]);
        		if(area>maxarea)maxarea=area;
        	}
        }
        return maxarea;
    }
}

(2)在O(n)的时间复杂度内解决问题

看到问题之后我一直在思考,这道题的最优解是否具有最优子问题的嵌套性质。想了半天没什么思路,还是跳出来放弃套路算法,好好分析一下。

注意到,在解法一中,我们每次都会从两个竹竿中选出一个最矮的作为计算高度对吧?那这不就是面积计算的短板了嘛。另一个较高的竹竿高度人家又没拖后腿,所以搜索的时候index的改变就不要动那个较高的竹竿了。由此思路,写出从数组两端向内开始搜索的代码,如下所示。

public class Solution {
	public int maxArea(int[] height) {
		int maxarea=0,area=0;
		for(int i=0,j=height.length-1;i<j;){
			if(height[i]>height[j]){
				area=(j-i)*height[j];
				j--;
			}
			else {
				area=(j-i)*height[i];
				i++;
			}
			if(area>maxarea)maxarea=area;
		}
		return maxarea;
	}
}


这样改进之后,效果非常好,毕竟是O(n)的代码呀,sub一下试试,果然AC,偷笑~~~





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值