11. Container With Most Water
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 and n is at least 2.
1 //这题我一开始理解错了,我以为全部能存下多少水,其实是找出哪2个挡板可以存下最多水,并返回水容量。下面代码是一开始理解错的。 2 3 /** 4 * @param {number[]} height 5 * @return {number} 6 */ 7 var maxArea = function(height) { 8 9 var len = height.length; 10 11 var left = 0,max = 0,right = len - 1,total = 0; 12 13 while(left < right){ 14 15 //比如 左边高度是 11 右边高度是 9, 根据短板原理,肯定 面积 = 9*底; 16 17 //双指针的解法 18 19 var min = Math.min(height[left],height[right]); 20 21 if(min > max){ 22 23 total += (min-max) * (right - left); 24 25 max = min; 26 27 } 28 29 height[left] > height[right] ? right-- : left++; 30 } 31 32 return total; 33 };
1 //正确代码 2 /** 3 * @param {number[]} height 4 * @return {number} 5 */ 6 var maxArea = function(height) { 7 8 var len = height.length; 9 10 var left = 0,max = 0,right = len - 1; 11 12 while(left < right){ 13 14 //比如 左边高度是 11 右边高度是 9, 根据短板原理,肯定 面积 = 9*底; 15 16 //双指针的解法 17 18 max = Math.max(max,Math.min(height[left],height[right]) * (right - left)); 19 20 21 height[left] > height[right] ? right-- : left++; 22 } 23 24 return max; 25 };