[LeetCode]11. Container With Most Water 盛最多水的容器

时间:2022-12-29 14:16:00

Given n non-negative integers a1, a2, ..., a, 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.

 

[LeetCode]11. Container With Most Water 盛最多水的容器

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

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

题目给出[a1,a2...ai],要求找出一个ai,aj是的min(ai,aj)*(j-i)最大。
有两种方法:
(1)暴力法
两层循环从左到右遍历,算出每一组的面积大小
public class Solution {
    public int maxArea(int[] height) {
        int maxarea = 0;
        for (int i = 0; i < height.length; i++)
            for (int j = i + 1; j < height.length; j++)
                maxarea = Math.max(maxarea, Math.min(height[i], height[j]) * (j - i));
        return maxarea;
    }
}

两层循环,复杂度自然是O(n^2)

(2)双指针法

现在假设[a1,a2......an],现在我们算出s=min(a1,an)*(n-1),1和n是长度的边界,剩下的任意高度组合的长度都不能比n-1大,长度如果变成了n-2,

之前算出的面积s如果不想变小,min(ai,aj)就必须比min(a1,an)大。总结一下就是,随着长度的缩小,面积要想变大就必须扩大高度,所以比原先高度低的我们就

不需要再考虑了。

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

一次遍历就能解决,时间复杂度O(n)