Leetcode 11 Container With Most Water
2015-07-25 10:23
393 查看
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.Solution1
这道题实际上是找到两根线,使得两根线之间能聚集的雨水最多,这和42题不一样。这里的思路是从数组两端开始,计算一次两根线之间能聚集多少雨水,完了将较短的那条边移动一格(移动方向是前面的指针往后移,后面的指针往前移),重新计算两根线之间能聚集多少雨水。public class Solution { public int maxArea(int[] height) { int result = 0; int n = height.length; for(int i=0,j=n-1;i<j;){ result = Math.max(result,Math.min(height[i],height[j])*(j-i)); if(height[i]<height[j]) i++; else j--; } return result; } }
Solution2
解法一比较直观易懂,但实际上计算了很多次不必要的迭代。因为当两根线往中间靠拢的时候,每次都是选择的最短那条边往中间移动,对于那些移动后比移动之前还要短的边实际上可以不需要考虑,只需要考虑移动后比移动前高的边就行,因为往中间移动的时候宽变窄了,只有较短的边变高之后才有可能使得整个的矩形面积最大。这种思路的代码如下:int result = 0; int n = height.length; for(int i=0,j=n-1;i<j;){ result = Math.max(result,Math.min(height[i],height[j])*(j-i)); if(height[i]<height[j]){ int k = i+1; while(k<j&&height[k]<=height[i]) k++;//将较短边往中间移动,知道找到一个比现有边更高的边 i = k; } else{ int k = j-1; while(k>i&&height[k]<height[j]) k--; j = k; } } return result;
Solution3
解法2在运行的时候比解法1更加高效,但是代码却没有解法一那么直白浅显。这里有一种不一样的代码实现,思想仍然是一样的。public class Solution { public int maxArea(int[] height) { int result = 0; for(int i=0,j=height.length-1;i<j;){ int h = Math.min(height[i],height[j]);//先找到最短的边 result = Math.max(result,h*(j-i)); while(i<j&&height[i]<=h) i++;//虽然有两个while循环,实际每次迭代的时候都只有最短边在移动直到比当前边高 while(i<j&&height[j]<=h) j--; } return result; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解