[LeetCode]-011-Container_With_Most_Water

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     }

 

posted @ 2016-04-18 10:53  练子  阅读(102)  评论(0编辑  收藏  举报