LeetCode做题笔记第11题:盛最多水的容器

题目描述

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/container-with-most-water

示例 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

解题思路

首先分析问题,盛水最多的时候,就是长乘宽最大的时候,长指的是数组下标的距离,宽指的是两条边中最短的一条边,采用双指针法可解决该问题,为了不错过最优的情况,left和right分别从两边开始往中间移动,每次只能移动一格,同时,比较左边和右边值的大小,那边的小那边的继续移动。直到左右指针相等。

完整代码

public class Solution {
    
    
    public int MaxArea(int[] height) {
    
    
            if (height.Length==2)
            {
    
    
                return 1*Math.Min(height[0], height[1]);
            }
            int left = 0;
            int right = height.Length-1;
            int maxArea = 0;
            while (left<right)
            {
    
    
                int area = (right-left)* Math.Min(height[left], height[right]);
                if (height[left]<height[right])
                {
    
    
                    left++;
                }
                else if (height[left]>height[right])
                {
    
    
                    right--;
                }
                else
                {
    
    
                    left++;
                    right--;
                }

                maxArea= maxArea>area ? maxArea : area;
            }
            return maxArea;
    }
}

Study hard and make progress every day.

猜你喜欢

转载自blog.csdn.net/u012869793/article/details/131379187