标签:
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.
思路:
假设有(i,A[i]),(j,A[j])构成的容器是目前发现的最大容器S;
则i的左边一定不存在k<i && A[k]>=A[i],否则与“目前发现的最大容器”这一假设矛盾;
同理,j的右边也不存在比A[j]大的线;
那么,可能的更大的容器在位于i,j之间。
取A[i]和A[j]较小的那个往中间移动(此时小的那个是瓶颈),
1. 如果i<k<j && A[K] <= A[i],继续移动;
2. 如果i<k<j && A[K] > A[i],则可能出现更大值,此时计算当前的面积S1
3. 如果S1 > S,更新S1
4. 在(i~k)或者(k~j)之间重复执行1-4步,直到i==j.
代码如下:
public int maxArea(int[] height) { if(height == null || height.length < 2) return 0; int left = 0; int currentLeft = height[left]; int right = height.length - 1; int currentRight = height[right]; int result = 0; while(left < right) { int tmp = Math.min(height[left], height[right]) * (right - left); if(tmp > result) { result = tmp; } currentLeft = height[left]; currentRight = height[right]; if(height[left] <= height[right]) { while(left < right && height[left] <= currentLeft) { left++; } } else { while(left < right && height[right] <= currentRight) { right--; } } } return result; }
更加详细的分析:http://www.tuicool.com/articles/v6Fryij
LeetCode-11 Container With Most Water
标签:
原文地址:http://www.cnblogs.com/linxiong/p/4324538.html