LeetCode 0011 盛水最多的容器(Java)

写在前面:
记录LeetCode练习过程,有自己的解决方法,也有借鉴了网上后实现的方法。方法不一定最优秀,但都是实践可用的。一些解释和理解写在程序起始的注释中。若有什么不当之处,欢迎留言交流,大家一起学习。

双指针法实现 LeetCode 0011 盛水最多的容器

/**
 * LeetCode 0011 盛水最多的容器
 * author: MammothKan
 * time: 2020/5/2
 * 题目描述:https://leetcode-cn.com/problems/container-with-most-water/
 * 解题思路:
 *      方法一:暴力枚举,即:遍历整个数组,罗列所有两两匹配的可能性并计算结果,时间复杂度为O(n*(n11)/2)
 *      方法二:双指针法,即:从数组的两端开始遍历,每次移动较小数值的那端,直到leftIndex>=rightIndex时结束,时间复杂度为O(n)
 *             下面解释一个问题,为什么每次一定值较小的那端的做法是可行的?
 *                  假设 leftHeight < rightHeight,
 *                  则 maxArea = min(leftHeight, rightHeight) * baseLeigth = leftHeight * baseLeigth;
 *                  此时若移动值较大端rightIndex,必然min(leftHeight, rightHeight) <= leftHeight成立,又因为baseLeigth--,所以maxArea必然越来越小,
 *                  至此,我们可以得出一个结论,较小端leftHeight的存在,不可能获得更大的maxArea,
 *                  所以,我们可以舍弃较小端,即移动铰小端的索引值。
 */

public class L0011盛水最多的容器 {

    public int maxArea(int[] height) {
        int baseLength = height.length-1;
        int leftIndex = 0;
        int rightIndex = height.length-1;
        int maxResult = 0;
        while (leftIndex < rightIndex) {
            maxResult = Integer.max(maxResult,
                    Integer.min(height[leftIndex], height[rightIndex]) * baseLength);
            if (height[leftIndex] < height[rightIndex]) {
                leftIndex += 1;
            }
            else {
                rightIndex -= 1;
            }
            baseLength--;
        }
        return maxResult;
    }

    public static void main(String[] args) {
        int[] height = {1,8,6,2,5,4,8,3,7};
        System.out.println(new L0011盛水最多的容器().maxArea(height));
    }

}

你可能感兴趣的:(LeetCode)