分享

LeetCode实战:盛最多水的容器

 老马的程序人生 2020-08-17

题目英文

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

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

题目中文

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

说明:你不能倾斜容器,且 n 的值至少为 2。

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

示例:

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

算法实现

利用暴力算法

public class Solution {
    public int MaxArea(int[] height) {
        int max = int.MinValue;
        for (int i = 0; i < height.Length - 1; i++)
        {
            for (int j = 1; j < height.Length; j++)
            {
                int temp = (j - i)*Math.Min(height[i], height[j]);
                if (temp > max)
                {
                    max = temp;
                }
            }
        }
        return max;        
    }
}

利用双指针算法

以0-7走到1-7这一步为例,解释为什么放弃0-6这一分支:

用h(i)表示第i条线段的高度,S(ij)表示第i条线段和第j条线段圈起来的面积。

已知 h(0) < h(7),从而S(07) = h(0) * 7

有S(06) = min(h(0), h(6)) * 6

当h(0) <= h(6),有S(06) = h(0) * 6
当h(0) > h(6),有S(06) = h(6) * 6,S(06) < h(0) * 6

由此可知,S(06)必然小于S(07)。

把每一棵子树按照同样的方法分析,很容易可以知道,双指针法走的路径包含了最大面积。

参考图文:

https:///problems/container-with-most-water/solution/zhi-guan-de-shuang-zhi-zhen-fa-jie-shi-by-na-kong/

public class Solution {
    public int MaxArea(int[] height) {
        int i = 0, j = height.Length - 1;
        int max = int.MinValue;
        while (i < j)
        {
            int temp = (j - i) * Math.Min(height[i], height[j]);
            if (temp > max)
            {
                max = temp;
            }
            if (height[i] < height[j])
            {
                i++;
            }
            else
            {
                j--;
            }
        }
        return max;        
    }
}

实验结果

利用暴力算法

  • 状态:超出时间限制

  • 49 / 50 个通过测试用例

利用双指针算法

  • 状态:通过

  • 50 / 50 个通过测试用例

  • 执行用时: 144 ms, 在所有 C# 提交中击败了 99.64% 的用户

  • 内存消耗: 26.6 MB, 在所有 C# 提交中击败了 5.45% 的用户
提交结果

相关图文

1. “数组”类算法

2. “链表”类算法

3. “栈”类算法

4. “队列”类算法

5. “递归”类算法

6. “字符串”类算法

7. “树”类算法

8. “哈希”类算法

9. “搜索”类算法

10. “动态规划”类算法

11. “数值分析”类算法


经过8年多的发展,LSGO软件技术团队在「地理信息系统」、「数据统计分析」、「计算机视觉」等领域积累了丰富的研发经验,也建立了人才培养的完备体系,由于自己准备在「量化交易」领域精进技能,如果大家对这个领域感兴趣可以与我联系,加入我们的量化学习群一起学习探讨。

在这个领域我已做了以下积累:

策略部分

数据部分

自动化交易部分


    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多