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

Container With Most Water

时间:2015-03-08 19:58:18      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路:

  双指针,减少短板

我的代码:

技术分享
public class Solution {
    public int maxArea(int[] height) {
        if(height == null || height.length <= 1)    return 0;
        int left = 0;
        int right = height.length - 1;
        int maxArea = Math.min(height[left],height[right])*(right - left);
        while(left < right)
        {
            int curLeft = left;
            int curRight = right;
            if(height[left] < height[right])
            {
                while(left < right && height[left] <= height[curLeft])
                {
                    left++;
                }
                maxArea = Math.max(Math.min(height[left],height[right])*(right - left), maxArea);
            }
            else
            {
                while(left < right && height[right] <= height[curRight])
                {
                    right--;
                }
                maxArea = Math.max(Math.min(height[left],height[right])*(right - left), maxArea);
            }
        }
        return maxArea;
    }
}
View Code

他人代码:

技术分享
public class Solution {
    public int maxArea(int[] height) {
        if (height == null) {
            return 0;
        }
        
        int left = 0;
        int right = height.length - 1;
        int maxArea = 0;
        
        while (left < right) {
            int h = Math.min(height[left], height[right]);
            int area = h * (right - left);
            maxArea = Math.max(maxArea, area);
            
            if (height[left] < height[right]) {
                // 如果左边界比较低,尝试向右寻找更高的边界
                left++;
            } else {
                // 如果右边界比较低,尝试向左寻找更高的边界
                right--;
            }
        }
        
        return maxArea;
    }
}
View Code

学习之处:

  • 思路一致,他人的代码更加简洁清楚,我的代码虽然循环多,但是时间复杂度是一致的,都是O(n),另外我的代码里面少计算了好多次maxArea

Container With Most Water

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4322150.html

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