[leetcode]Container With Most Water
2013-07-27 14:38
246 查看
此题一开始看错了,后来才发现由小的一根(短板)决定高度。中间看过网上的解答,思路是O(n)的,略巧妙。其实就是基于这样一个直觉,先把L1设为最左,R1设为最右,这样宽度最大,然后缩小宽度,那么高度就要比原来高。缩小宽度的逻辑是,如果L1比R1小,那么L1往右移,否则反之。可以做简单证明。
如图,L1<R1<R2<L2,那么在L1移动到L2和R1移动到R2的过程中,存在的Lx和Rx都满足Lx < L1, Rx < R1。假设Lx < Rx,那么Lx* d(Rx - Lx) < L1*d(Rx-Lx) < L1 * ( R1 - L1)。若Lx > Rx,则Rx * d(Rx - Lx) < Rx * d(R1 - L1) < L1 * d(R1 - L1) (因为Rx,Lx都小于L1<R1)。直观的想就是,如果宽度减少,同时左右两侧的板都比原来的还要矮,怎么可能容纳更多的水呢?
所以画图还是很有用的。而且,一次过,爽。
如图,L1<R1<R2<L2,那么在L1移动到L2和R1移动到R2的过程中,存在的Lx和Rx都满足Lx < L1, Rx < R1。假设Lx < Rx,那么Lx* d(Rx - Lx) < L1*d(Rx-Lx) < L1 * ( R1 - L1)。若Lx > Rx,则Rx * d(Rx - Lx) < Rx * d(R1 - L1) < L1 * d(R1 - L1) (因为Rx,Lx都小于L1<R1)。直观的想就是,如果宽度减少,同时左右两侧的板都比原来的还要矮,怎么可能容纳更多的水呢?
所以画图还是很有用的。而且,一次过,爽。
public class Solution { public int maxArea(int[] height) { // Start typing your Java solution below // DO NOT write main() function int ans = 0; int tmp = 0; int l = 0; int r = height.length - 1; while (l < r) { int min = Math.min(height[l], height[r]); tmp = min * (r - l); if (tmp > ans) ans = tmp; if ( height[l] < height[r]) { int last = height[l]; while (l < r && height[l] <= last) { l++; } } else { int last = height[r]; while (l < r && height[r] <= last) { r--; } } } return ans; } }
相关文章推荐
- 【leetcode】Container With Most Water
- Leetcode-11:Container With Most Water
- LeetCode 11 Container With Most Water(分支判断问题)
- leetcode 11 -- Container With Most Water
- 【Leetcode】Container With Most Water
- [LeetCode] Container With Most Water
- leetcode Container With Most Water
- LeetCode 011 Container With Most Water *
- LeetCode - Container With Most Water
- LeetCode | #11 Container With Most Water
- leetcode-- Container With Most Water
- [LeetCode]Container With Most Water
- leetcode — container-with-most-water
- LeetCode 之 Container With Most Water — C 实现
- LeetCode 11 Container With Most Water
- leetcode之11. Container With Most Water(C++解法)
- LeetCode-Container With Most Water
- Leetcode 11 Container With Most Water
- leetcode11 Container With Most Water
- 【Leetcode】【python】Container With Most Water