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.
简单方法就是暴力破解,不过肯定会超时。
仔细想想,可以使用双指针指向数组头尾解决。需要注意的就是短板问题,要想获取较大的容量,只能通过移动较小的指针,否则肯定变小。
1 public class ContainerWithMostWater { 2 public static int maxArea(int[] height){ 3 int maxarea = 0; 4 int area = 0; 5 int l = 0; 6 int r = height.length - 1; 7 while( l < r){ 8 area = min(height[l] , height[r]) * ( r - l); 9 if ( area > maxarea) 10 maxarea = area; 11 12 if( height[l] < height[r]) 13 l++; 14 else 15 r--; 16 } 17 return maxarea; 18 } 19 20 static int min( int a,int b){ 21 return a>b ? b : a; 22 } 23 }
posted on 2015-07-28 17:10 myshuangwaiwai 阅读(152) 评论(0) 编辑 收藏 举报