Leetcode 11 container with most water解析

本文解析了LeetCode11题目的算法思路,通过双指针法求解盛水最多的容器问题,详细解释了如何通过控制变量来降低算法复杂度。

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

解析:
这道题有3个变量, 左端endpoint,右端endpoin,左右endpoint间的x轴长度
这里把endpoint处的数组变量称作木板的长度
目的是找出MaxArea=min(左端木板长度,右端木板长度)*左右间x轴长度

也就是说一个桶能装多少水取决于最短的那块木板的长度

3个变量同时变化的话,就需要遍历所有值才能找出最大值,如果能控制住两个变量单调递减或不变,只去增大一个变量就可以降低复杂度。

(1)左右间x轴长度
如果取left指针指向左端木板,right指针指向右端木板,那么开始时x轴长度是最大值。
然后left, right由两端向中间走,x轴长度保证为单调递减。
这时想找maxArea则只需要考虑左端木板长度和右端木板长度取较大的值。

(2)左右木板长度保留较长的
所谓桶能装多少水取决于最短的木板长度,那么就要保证要留下左右木板中较长的那块,
然后移动较短那端的指针,才有可能遇到maxArea。
如果保留较短的,那么无论另一端有多长,maxArea都不会大。
比如数组{1, 2, 4, 3}
开始left指向1, right指向3,这时area= (3-0)*min(1,3) = 3
保留较长的3,移动left至2, 这时area= (3-1)*min(2,3) = 4
保留较长的3,移动left至4, 这时area= (3-2)*min(4,3) = 3
可以找出maxArea=4

   public static int maxArea(int[] height) {
	   int left = 0;
	   int right = height.length-1;
	   int area = 0;
	   int maxArea = 0;
	   
	   while(left < right){
		   area = (right-left)*Math.min(height[left], height[right]);
		   if(area > maxArea) {
			   maxArea = area;
		   }
		   if(height[left] < height[right]){
			   left++;
		   } else {
			   right--;
		   }
	   }
	   return maxArea;
   }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值