美文网首页
Leecode[11] 盛最多水的容器

Leecode[11] 盛最多水的容器

作者: 饭板板 | 来源:发表于2020-09-23 14:24 被阅读0次

题目

给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

思路解析

  • 设置双指针,根据规则移动指针。
  • 设置水槽面积位 S(i,j),由于水槽的实际高度由两板中的短板决定,则可得面积为 S(i,j)=min(h[i],h[j])×(j−i)。
  • 指针移动时,无论长板或短板收窄一格,都会导致水槽 底边宽度 -1:
    • 若向内移动短板,水槽的短板 min(h[i], h[j]) 可能变大,因此水槽面积可能变大。
    • 若向内移动长板,水槽的短板 min(h[i], h[j]) 不变或者变小,因此水槽面积一定小于当前水槽面积。
public class Solution {
    public int MaxArea(int[] height) {
        int i=0,j=height.Length-1, res=0;
        while(i<j)
        {
            res=height[i]<height[j]?
            Math.Max(res,(j-i)*height[i++]):
            Math.Max(res,(j-i)*height[j--]);
        }
        return res;
    }
}

举一反三

求水槽容纳最少的水。

public static int MinArea(int[] height)
{
    int i = 0, j = height.Length - 1, res = int.MaxValue;
    while (i < j)
    {
        if (height[i] < height[j])
        {
            res = Math.Min(res, (j - i) * height[i]);
            j--;
        }
        else
        {
            res = Math.Min(res, (j - i) * height[j]);
            i++;
        }
    }

    return res;
}

求容纳最少水,就是对数组进行排列,求出最小元素。

相关文章

网友评论

      本文标题:Leecode[11] 盛最多水的容器

      本文链接:https://www.haomeiwen.com/subject/zonnyktx.html