首页 > 其他 > 详细

LeetCode 11 -- Container With Most Water

时间:2015-07-28 20:26:09      阅读:229      评论:0      收藏:0      [点我收藏+]

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). 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 }

 

LeetCode 11 -- Container With Most Water

原文:http://www.cnblogs.com/myshuangwaiwai/p/4683479.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!