Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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.
直接BF方法,两个循环,时间复杂度为O(n^2).只能跑过小数据,大数据直接挂了
1 public int maxArea(int[] height) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 int start = 0; 5 int end = height.length - 1; 6 int size = height.length; 7 int max = 0; 8 for(int i = 0; i < end; i++){ 9 for(int j = end; j > i; j--){ 10 int container = Math.min(height[i], height[j]) * (j - i); 11 if(container > max) 12 max = container; 13 } 14 } 15 return max; 16 }
参考http://www.mitbbs.com/article_t/JobHunting/32184909.html
本题可以有O(n)时间复杂度的解法,容器容量大小的短板在高度小的那侧,如果height[start] < height[end], 则如果想要是容量变大,唯一做法是使height[start]变大,则start++。height[start] < height[end]时同理使end--
1 public int maxArea(int[] height) { 2 int start = 0; 3 int end = height.length - 1; 4 int size = height.length; 5 int max = 0; 6 while(start < end){ 7 int container = Math.min(height[start], height[end]) * (end - start); 8 if(max < container){ 9 max = container; 10 } 11 12 if(height[start] > height[end]){ 13 end --; 14 } else { 15 start ++; 16 } 17 } 18 19 return max; 20 }