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

[LeetCode]-011-Container_With_Most_Water

时间:2016-04-18 11:23:25      阅读:134      评论: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.

Note: You may not slant the container.

题目大意:求一系列点之间的最大面积

第一种方法:时间复杂度(O(n^2))

 1 public int maxArea(int[] height) {
 2     int area = 0;
 3     int min = 0;
 4     for(int i=0; i<height.length; i++){
 5         for(int j=i+1; j<height.length; j++){
 6             if(height[i] == height[j])
 7                 area = Math.max(area, height[i]*(j-i));
 8             else{
 9                 min = Math.min(height[i],height[j]);
10                 area = Math.max(area, min*(j-i));
11             }
12         }
13     }
14     return area;
15 }

第二种方法:

 1 public int maxArea(int[] height) {
 2         int area = 0;
 3         int begin = 0;
 4         int end = height.length-1;
 5         while(begin<end){
 6             area = Math.max(area, (end-begin)*Math.min(height[begin],height[end]));
 7             if(height[begin]<height[end])
 8                 begin++;
 9             else
10                 end--;
11         }
12         return area;
13     }

 

[LeetCode]-011-Container_With_Most_Water

标签:

原文地址:http://www.cnblogs.com/lianliang/p/5403602.html

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