LeetCode_Container With Most Water

32 篇文章 0 订阅

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

题目:输入一个整形数组,如a=[ 2,4,6,3,5 ],数字的大小为挡板的高度,两两数字的间距为挡板的间距,比如4和3两个挡板之间的水容量就是两个数字之差乘以两数字的间距,即(4-3)*(3-1)= 2,假设两个数字在该数组中的序号为i,j(i<j),那么总结计算公式就是:(j - i)*(min(a[ i ],a[ j ]))。

题目清楚之后,开始考虑,如果两次遍历是可以求出来的,但是时间复杂度O(n^2)太大。另一种方法,假设已经找出了这两个挡板i和j(i<j),那么在i的左边的所有数字都小于i,在j的右边的所有数字都小于j,反证法可以证明。那么就从数组两端开始向中间靠近,每次选取两个数字较小的一个向中间靠近(为什么选较小的一个呢,假如选了较大的一个来处理,即使下一个比较大的那个还要大,但是由以上计算公式得,min(a[ i ],a[ j ])还是较小的那个挡板,并且(j - i)更小了,所以一定是选择较小的那个挡板向中间靠拢,并且直到找到比较小的那个数字大的一个数字),这样线性复杂度内就可以解题了。

java解题:

public static int maxArea(int[] height) {
		int i=0,j=height.length-1,temp=0,max=0;
		while(i<j){
			max=Math.max(max, (j-i)*Math.min(height[i],height[j]));
			if(height[i]<height[j]){
				temp = i;
				while(temp<j && height[temp]<=height[i])
					temp++;
				i=temp;
			}
			else{
				temp = j;
				while(i<temp && height[temp]<=height[j])
					temp--;
				j=temp;
			}
		}
		return max;
	}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值