码迷,mamicode.com
首页 > 其他好文 > 详细

Container With Most Water

时间:2015-02-03 20:55:30      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

https://oj.leetcode.com/problems/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.

解题思路:

这是一道很巧妙的题目。根据短板原理,这个容器能容的水量,应该是两个很坐标的差,也就是宽,乘以两个竖线中较短的那个。如果使用暴力法,显然需要对比n个竖线两两的组合,时间复杂度为O(n^2)。一般的,这样的解法都会超时,必须要寻找更为好的方法。

我们这里使用两个游标,分别指向a1和an,向中间靠近,直到两者相等。如果左侧的小,则左侧坐标++,如果右侧小,则右侧坐标--。考虑一下为什么这样就可以了?

还是因为面积是由宽和较短的那根竖线决定的。如果左侧的较短,右侧再往内收,宽就更小,竖线也不会超过左侧的高度了,反而可能更低,显然已经到了最大值。所以只能将左侧的竖线内收,右边不懂,寻找在宽变小的情况下,可能的更长的竖线。

这道题用了两个pointers,在线性时间内就得到了解,值得好好体会。

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

 

Container With Most Water

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4270861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!