LeetCode题解-11-Container With Most Water
2017-03-04 21:58
471 查看
解题思路
题意是说,有一堆有序的数字ai,要计算min(ai,aj)*abs(i-j)的最大值,普通的算法就是列举所有的情况,时间复杂度是O(n^2)。下面介绍一下O(n)的思路。首先记录左边是left,右边是right,那么初始化max就是左右两边组成的值。
假设左边比较小。
如果left+i比left的值要小,那么由left+i和right组成的值会更小,而left和left+1组成的值也是更小的。
如果left+i比left的值要大,那么由left+i和right组成的值可能会更大或更小,而left和left+1组成的值是更小的。
那么就可以从左边渐进一个位置,直到找到一个left+i的值比left要大,让值和max去比较。
右边较小的情况是类似的,最终left会超过right,这个时候就结束了。
参考源码
public class Solution { public int maxArea(int[] height) { int max = 0; if (height == null || height.length < 2) { return max; } int left = 0; int right = height.length - 1; while (left < right) { int tmax = (right - left) * Math.min(height[left], height[right]); if (tmax > max) { max = tmax; } if (height[left] < height[right]) { int t = left; while (t < right && height[t] <= height[left]) { t++; } left = t; } else { int t = right; while (t > left && height[t] <= height[right]) { t--; } right = t; } } return max; } }
相关文章推荐
- LeetCode(11)题解: Container With Most Water
- 11. Container With Most Water LeetCode题解
- Leetcode题解:11. Container With Most Water
- [LeetCode]11 Container With Most Water
- leetcode题解||Container With Most Water问题
- LeetCode 11 - Container With Most Water
- [leetcode 11]Container With Most Water
- leetcode 11 -- Container With Most Water
- [leetcode 11] Container With Most Water
- Java [leetcode 11] Container With Most Water
- LeetCode 11 Container With Most Water
- LeetCode 11 Container With Most Water (C,C++,Java,Python)
- LeetCode_11---Container With Most Water
- LeetCode42/11 Trapping Rain Water/Container With Most Water/Hist area**
- LeetCode 11 - Container With Most Water
- leetcode[11]Container With Most Water
- leetcode 11 Container With Most Water
- LeetCode-11 Container With Most Water(容器装水最大量)
- [Leetcode 43] 11 Container With Most Water
- leetcode_11题——Container With Most Water(两个指针)