LeetCode 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.
Note: You may not slant the container and n is at least 2.
题目标签:Array
这道题目给了我们一个height array, 每一个数字代表一条竖直线的高度,从x轴开始。一开始用暴力法没通过。所以要用特别方法来做。分析一下,如何才能够拿到更多的水。如果一根线很低,另外一根很高,那么水只能装到低的那根线,等于把高出的区域浪费了。那么需要找到更高的线来替代低的那条才有希望找到装水更多的两条线。设两个pointer,left 和 right。 从最两边开始遍历,每一次都计算面积,比max大的话就替换。接着把低的那根线的pointer 向另外一边移动,直到两个pointers 相遇。
Java Solution:
Runtime beats 31.31%
完成日期:07/11/2017
关键词:Array
关键点:Two Pointers
1 public class Solution 2 { 3 public int maxArea(int[] height) 4 { 5 int left = 0; 6 int right = height.length-1; 7 int max_area = -1; 8 9 while(left < right) 10 { 11 int len = right - left; 12 int ht = Math.min(height[left], height[right]); 13 max_area = Math.max(max_area, len*ht); 14 15 if(height[left] < height[right]) 16 left++; 17 else 18 right--; 19 20 } 21 22 return max_area; 23 } 24 }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List