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;
}
本文解析了LeetCode11题目的算法思路,通过双指针法求解盛水最多的容器问题,详细解释了如何通过控制变量来降低算法复杂度。
7500

被折叠的 条评论
为什么被折叠?



