码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 11 -- Container With Most Water

时间:2015-07-28 20:26:35      阅读:96      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!