Container With Most Water
2013-11-30 10:08
141 查看
public int maxArea(int[] height) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int i = 0; int j = height.length-1; int max=0,temp =0; while(i<j){ temp = (j-i)*(height[i]>height[j]?height[j]:height[i]); if(temp>max){ max = temp; } if(height[i]<height[j]){ i++; }else{ j--; } } return max; }设置两个指针,从两头往中间靠拢,如果右边高,则保留右边,左边加1,;左边高,则保留左边,右边减1
证明:不管是左边加1还是右边减1,容器在x轴上的长度都减少了。一次计算完后,这时,有两个选择,要么左边加1,要么右边减1
如何选择,就看左边高还是右边高了。为什么要保留高的?
设a<b,a=height[i],b=height[j],c=height[i+1],d=height[j-1];
在移动指针之前,maxArea=(j-i)*a;
假设移动左边的指针,则maxArea1=(j-i-1)*min(c,b),有可能大于maxArea
如果移动右边的指针,则maxArea2=(j-i-1)*min(a,d)<maxArea=(j-i)*a
移动右边的指针,得到的面积肯定比移动指针前小,那就没必要考虑这种情况,所以要移动左边的指针。
相关文章推荐
- LeetCode 011: Container With Most Water
- Container With Most Water
- 11. Container With Most Water
- 011_LeetCode_11 Container With Most Water 题解
- leetcode 11:Container With Most Water
- 11. Container With Most Water
- container-with-most-water
- [LeetCode 11] Container With Most Water
- Container With Most Water
- LeetCode-11:Container With Most Water
- 【leetcode】Container With Most Water
- container with most water
- 11. Container With Most Water(重要!)
- leetcode--Container With Most Water
- Container With Most Water
- leetcode_Container With Most Water
- 11 Container with most water
- LeetCode_container-with-most-water
- LeetCode-11~Container with Most Water
- leetcode Container With Most Water