标签:
题目描述:
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.
解题思路:
先找距离最长的两个位置看能装下多少水,随后缩小两边的距离,因为距离减少,所以要先使得所能容纳的水变多,只能提高形成的“桶”的高度。因为高度与最低的边界一致,所以缩小边界时要从值小的那一边找,知道找到大于“桶高”的值,说明桶的高度可以得到提升,计算新桶所能容纳的体积并与最大值比较。以此类推,知道两边不能在缩小位置。
具体代码:
1 public class Solution { 2 public static int maxArea(int[] height) { 3 if(height==null||height.length<=0) 4 return 0; 5 if(height.length==2){ 6 int n=Math.min(height[0], height[1]); 7 return n; 8 } 9 10 11 int from=0; 12 int to=height.length-1; 13 int min=Math.min(height[from], height[to]); 14 int max=(to-from)*min; 15 while(from<to){ 16 if(height[from]<=height[to]){ 17 from++; 18 while(from<to && height[from]<=min){ 19 from++; 20 } 21 } 22 else{ 23 to--; 24 while(from<to && height[to]<=min){ 25 to--; 26 } 27 } 28 min=Math.min(height[from], height[to]); 29 int area=(to-from)*min; 30 if(max<area) 31 max=area; 32 } 33 return max; 34 } 35 }
【leetcode】11. Container With Most Water
标签:
原文地址:http://www.cnblogs.com/godlei/p/5582607.html