算法练习- LeetCode 11. 盛最多水的容器

今日心情:重新启程!

题目描述:

LeetCode 11. 盛最多水的容器

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

说明:你不能倾斜容器。


解题代码:

class Solution {
    public int maxArea(int[] height) {
        // 
        int len = height.length;
        if(height == null || len <=1){
            return 0;
        }
        
        //
        int left = 0;
        int right = len -1;
        int maxContainer = Integer.MIN_VALUE;
        
        while(left < right){
            int curArea = calcArea(height,left,right);
            maxContainer = Math.max(maxContainer,curArea);
            
            if(height[left] < height[right]){
                left++;
            }else{
                right--;
            }
        }
      
        
        return maxContainer;
    }
    
    //calculate the area
    public int calcArea(int[] height, int l, int r){
        
        int bottom = r-l;
        
        return (height[l] >= height[r]) ? height[r]*bottom : height[l]*bottom;
        
    }
}

解题思路:

自己想的方案和题解差不多,自己写的时候主要在如何移动指针进行二分的时候想的过于复杂,不知道怎么实现移动左右指针。看题解才发现自己想的过于复杂,其实只要判断左边的高度和右边的高度,下面的底其实不用考虑,因为是搜索找最大值,所以最后只会保留最大的值。最高的高度就没有必要移动了,因为它是能找到最大的面积值的充分不必要条件。

代码思路:

(1)要计算面积,此处首先想到了用一个helper方法。但实际上使用 

Math.min(height[left],height[right]) * (right - left) 就可以进行最大 container 面积计算

    //calculate the area
    public int calcArea(int[] height, int l, int r){
        
        int bottom = r-l;
        
        return (height[l] >= height[r]) ? height[r]*bottom : height[l]*bottom;
        
    }

(2)空数组和不满足container条件判断,不符合则返回0;

(3)双指针 left 和 right , 进行二分搜索。首先计算 左右 指针处围成的container的面积值,然后update 最大值。

(4)移动左右指针条件:如果左边高度 大于 右边高度 height[left] < height[right],左边指针 left 加一,以搜索最高的高度为目的;:如果右边高度 大于等于 左边高度 height[left] >= height[right],右边指针 rigth 加一,以搜索最高的高度为目的移动指针。

(5)搜索更新结束之后,返回 maxContainer (此时为最大的container值).


小结:

        主要需要确定的点就是:如何移动左右指针实现搜索查找更新

猜你喜欢

转载自blog.csdn.net/qq_41758969/article/details/125672574