首页 > 其他 > 详细

11. Container With Most Water (Array)

时间:2018-07-31 10:37:10      阅读:146      评论:0      收藏:0      [点我收藏+]

O(n)的方法,两边开始计算最wide的container, 因为往中间走的话,要想遇到更max的,需要更高的smaller height,因此可以去掉已经计算过的smaller的height。

 

 1 //Old
 2 class Solution {
 3     public int maxArea(int[] height) {
 4         int max = 0;
 5         int size = height.length;
 6         for(int i = 0; i < size - 1; i++) {
 7             for(int j = i + 1; j < size; j++) {
 8                 int lower = height[i] < height[j] ? height[i]:height[j];
 9                 if(max < lower * (j - i)) {
10                     max = lower * (j - i);
11                 }
12             }
13         }
14         return max;
15     }
16 }
17 
18 //New
19 
20 class Solution {
21     public int maxArea(int[] height) {
22         int max = 0;
23         int size = height.length;
24         int l = 0, r = size - 1;
25         while(l < r) {
26             int current = Math.min(height[l], height[r]) * (r - l);
27             if(current > max) max= current;
28             if(height[l] < height[r]) {
29                 l++;
30             }else {
31                 r--;
32             }
33         }
34         return max;
35     }
36 }

 

11. Container With Most Water (Array)

原文:https://www.cnblogs.com/goPanama/p/9393783.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!