leetcode|中等:11. 盛最多水的容器

jupiter
2022-03-24 / 0 评论 / 491 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年03月24日,已超过757天没有更新,若内容或图片失效,请留言反馈。

1.题目

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

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

说明:你不能倾斜容器。

示例 1:

输入:[1,8,6,2,5,4,8,3,7]
输出:49 
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例 2:

输入:height = [1,1]
输出:1

提示:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

2. 题解

2.1 思路分析

思路1:双指针
设两指针 i,j ,指向的水槽板高度分别为 h[i], h[j] ,此状态下水槽面积为 S(i,j)。由于可容纳水的高度由两板中的 短板 决定,因此可得如下 面积公式 :
                    S(i, j) = min(h[i], h[j]) × (j - i)
在每个状态下,无论长板或短板向中间收窄一格,都会导致水槽 底边宽度 -1 变短:
    若向内移动短板,水槽的短板 min(h[i],h[j])可能变大,因此下个水槽的面积可能增大 
    若向内移动长板,水槽的短板 min(h[i],h[j])不变或变小,因此下个水槽的面积一定变小 
因此,初始化双指针分列水槽左右两端,循环每轮将短板向内移动一格,并更新面积最大值,直到两指针相遇时跳出;即可获得最大面积。

2.2 代码实现

public class Solution {
    public int maxArea(int[] height) {
        int max = 0;
        int left = 0,right = height.length-1; // 双指针

        while (left<right){
            int area = Math.min(height[left],height[right])*(right-left);
            max = Math.max(area,max);

            if(height[left]>height[right]){
                right--;
            }else {
                left++;
            }
        }

        return max;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.maxArea(new int[]{1,8,6,2,5,4,8,3,7}));
    }
}

2.3 提交结果

提交结果执行用时内存消耗语言提交时间备注
通过4 ms51.6 MBJava2022/03/24 12:32添加备注

参考资料

  1. https://leetcode-cn.com/problems/container-with-most-water/
  2. https://leetcode-cn.com/problems/container-with-most-water/solution/container-with-most-water-shuang-zhi-zhen-fa-yi-do/
0

评论 (0)

打卡
取消