LeetCode11. Container With Most Water 解题报告

Posted 月盡天明

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode11. Container With Most Water 解题报告相关的知识,希望对你有一定的参考价值。


转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51820937


Subject

出处:https://leetcode.com/problems/container-with-most-water/


Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.


Explain

给定n个非负的整数a1,a2 ……an, 去哦中每个代表一个点坐标(i, ai)。一共n个垂直线段。找到两个线段,与X轴形成一个容器,使其能剩最多的水。

其实就是找到这两条线段之后,用最短的线段的长度 * 两个线段之间的距离。


Solution

solution 1

通过嵌套循环来做。很明显,这是比较笨的方法,也是最容易想到的方法。

时间复杂度也就是o(n²)了。

    /**
     * 时间复杂度o(n²)
     * 
     * @param height
     * @return
     */
    public int maxArea1(int[] height) {
        if (height == null || height.length < 2) {
            return 0;
        }
        int result = 0;
        int temp = 0;
        for (int i = 0; i < height.length; i++) {
            for (int j = i + 1; j < height.length; j++) {
                temp = (j - i) * Math.min(height[i], height[j]);
                if (temp > result) {
                    result = temp;
                }
            }
        }
        return result;
    }

solution 2

通过两个“指针”,分别指向头和尾。

分别往中间移动,
当 “左指针” 指向的线段长度小于“右指针”指向的线段长度,则移动 “左指针” 。
反之,移动“右指针”。

    /**
     * 
     * @param height
     * @return
     */
    public int maxArea2(int[] height) {
        if (height == null || height.length < 2) {
            return 0;
        }
        int left = 0;
        int right = height.length - 1;
        int result = 0;
        int temp = 0;

        while (left < right) {
            temp = (right - left) * Math.min(height[left], height[right]);
            result = Math.max(result, temp);
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }

        return result;
    }

时间复杂度是o(n)。


bingo~~

以上是关于LeetCode11. Container With Most Water 解题报告的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode?????????python?????????11. Container With Most Water

LeetCode11. Container With Most Water 解题报告

leetcode_11. Container With Most Water

Leetcode 11. Container With Most Water (two pointers)

LeetCode 11. Container With Most Water

leetcode11 Container With Most Water