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

【leetcode】11. Container With Most Water

时间:2016-06-14 06:19:00      阅读:150      评论: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 (iai) 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!