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

11. Container With Most Water

时间:2016-05-11 14:56:12      阅读:130      评论: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 int maxArea(int[] height) {
 3         int max=0;
 4         for(int i=0;i<height.length-1;i++)
 5         {
 6             int min=height[i];
 7             for(int j=i+1;j<height.length;j++)
 8             {
 9                 if(min>height[j])
10                 min=height[j];
11                 if(min*(j-i)>max)
12                 max=min*(j-i);
13             }
14         }
15        return max;
16     }
17 }

 代码如下:(方法二:Accept)

 1 public class Solution {
 2     public int maxArea(int[] height) {
 3         
 4         int left=0,right=height.length-1;
 5         int max=Math.min(height[0],height[height.length-1])*(right-left);
 6         
 7         while(left<right)
 8         {
 9             if(height[left]<=height[right])
10             {
11                 if(height[left]*(right-left)>max)
12                 max=height[left]*(right-left);
13                 left++;
14             }
15             else{
16                 if(height[right]*(right-left)>max)
17                 max=height[right]*(right-left);
18                 right--;
19             }
20         }
21         return max;
22     }
23 }

 

11. Container With Most Water

标签:

原文地址:http://www.cnblogs.com/ghuosaao/p/5481681.html

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