Leecode[11] 盛最多水的容器

2020-09-23  本文已影响0人  饭板板

题目

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

思路解析

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;
}

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

上一篇 下一篇

猜你喜欢

热点阅读