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 }