leetcode解题之 11. Container With Most Water Java版(最大盛水容积)
2017-04-06 15:13
405 查看
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.
找两条竖线然后这两条线以及X轴构成的容器能容纳最多的水。
假设先选取的是两端之间的两条线段,这样这两条线段之间的距离是最大的,长度是给定数组的长度减1。那么在这种情况下要容纳更多的水,由于宽度已经是最大的了,只能想法提高线段的高度,这种情况下如果两端是左边比右边高,那么只有可能是将左边的指针右移,否则将右边的指针左移,然后这右回到了初始的问题,这样不断移动下去到左右指针相等为止
// leetcode此种方法有时TLE,有时AC public int maxArea1(int[] height) { if (height == null || height.length == 0) return 0; int left = 0; int right = height.length - 1; int maxArea = 0; while (left < right) { maxArea = Math.max(Math.min(height[left], height[right]) * (right - left), maxArea); if (height[left] <= height[right]) left++; else right--; } return maxArea; } // 优化版 public int maxArea(int[] height) { if (height == null || height.length == 0) return 0; int left = 0; int right = height.length - 1; int maxArea = 0; while (left < right) { // 设算当前的最大值 maxArea = Math.max(Math.min(height[left], height[right]) * (right - left), maxArea); if (height[left] <= height[right]) { int k = left; // 如果letf右边的高度比left的高度小,面积不可能比之前大,所以 // 从[left, right - 1]中,从左向右找, //找第一个高度比height[left]高的位置 while (k < right && height[k] <= height[left]) k++; left = k; } else { int k = right; // 如果right左边的高度比right的高度小,面积不可能比之前大,所以 // 从[left + 1, right]中,从右向左找, //找第一个高度比height[right]高的位置 while (k > left && height[k] <= height[right]) k--; // 从[left, right - 1]中,记录第一个比原来height[right]高的位置 right = k; } } return maxArea; }
相关文章推荐
- leetcode解题之Maximum/Minimum Depth of Binary Tree Java版(树的最大、最小深度)
- leetcode解题之124. Binary Tree Maximum Path Sum Java版 (二叉树的最大路径和)
- [leetcode]分治法求解最大子序列问题——Java实现
- LeetCode Plus One Java版解题报告
- 解题报告:LeetCode Largest Rectangle in Histogram(计算最大矩形面积)
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- LeetCode: 8. String to Integer 【java 解题】
- 【leetcode Java】二叉树的递归遍历以及最大深度的求解(Java)
- [LeetCode] 205. Isomorphic Strings 解题思路 - Java
- Ugly Number | leetcode 263 【Java解题报告】
- Move Zeroes | leetcode 283 【Java解题报告】
- 【LeetCode】Merge Two Sorted Lists 解题报告(Java & Python)
- [C++]LeetCode 11: Container With Most Water(最大容积/最大矩形面积)
- 【LeetCode-面试算法经典-Java实现】【053-Maximum Subarray(最大子数组和)】
- leetCode 85.Maximal Rectangle (最大矩阵) 解题思路和方法
- Climbing Stairs | leetcode 70 【Java解题报告】
- 景岁的Leetcode解题报告:147.Insertion Sort List (Java)
- leetCode 84.Largest Rectangle in Histogram (最大矩形直方图) 解题思路和方法
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- leetCode 53.Maximum Subarray (子数组的最大和) 解题思路方法