LeetCode 11. Container With Most Water--Java 解法--困雨水简单版

2020/01/21 LeetCode 共 760 字,约 3 分钟

题目地址:Container With Most Water - LeetCode


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.

Note: You may not slant the container and n is at least 2.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

很奇怪这道题目我这么晚才看到,之前看到LeetCode 42. Trapping Rain Water时觉得题目怎么这么难,现在才发现,原来这道题目是简化版的困雨水。

这道题目难度的降低在于柱子是没有体积的,

暴力破解的自然会超时,如果从2遍向中间夹即可遍历一遍。

Java解法如下:

class Solution {
    public int maxArea(int[] height) {
        int maxarea = 0, left = 0, right = height.length - 1;
        while (left < right) {
            maxarea = Math.max(maxarea, Math.min(height[left], height[right]) * (right - left));
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return maxarea;
    }
}

文档信息

Table of Contents