Container With Most Water

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
原文地址:https://www.cnblogs.com/sunshisonghit/p/4322150.html