Container With Most Water Leetcode

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.

 

 
这道题乍一看很吓人,但其实如果一开始想不到最优的解法,可以试着从暴力解法入手,就能想到更好的方法了。另外two pointers应用挺多的,可以首先想一下。
实现很简单。。。稍稍优化下就和top solution一样啦
public class Solution {
    public int maxArea(int[] height) {
        int max = 0;
        int left = 0;
        int right = height.length - 1;
        while (left < right) {
            max = Math.max(max, Math.min(height[left], height[right]) * (right - left));
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return max;
    }
}

 

做第二遍的时候,其实严重怀疑自己当时并没有完全理解这道题目。。。

为什么左边比右边小就可以移动左边的pointer了?原因是大概是一个因子变小了,另一个要变大才有可能使得总量超过原来的值。懒得看证明了。。。要是面试面到就这么说好了。。。= = 到时候有精力再回顾下吧。。。

posted @ 2017-01-26 03:37  璨璨要好好学习  阅读(97)  评论(0编辑  收藏  举报