LeetCode 11. Container With Most Water (装最多水的容器)

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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

 public class Solution
{
public int maxArea(int[] height)
{
int left = 0;
int right = height.length-1;
int max_area = -1; while(left < right)
{
int len = right - left;
int ht = Math.min(height[left], height[right]);
max_area = Math.max(max_area, len*ht); if(height[left] < height[right])
left++;
else
right--; } return max_area;
}
}

参考资料:N/A

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

上一篇:Leetcode 11. Container With Most Water(逼近法)


下一篇:Leetcode: Reorder List && Summary: Reverse a LinkedList