博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode】1. 盛最多水的容器:C#三种解法
阅读量:4033 次
发布时间:2019-05-24

本文共 1671 字,大约阅读时间需要 5 分钟。

题目:https://leetcode-cn.com/problems/container-with-most-water/

盛最多水的容器

难度:中等

给你 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 int MaxArea(int[] height)    {        // 解法1:        int res = 0;        for (int i = 0; i < height.Length; i++)        {            for (int j = i + 1; j < height.Length; j++)            {                int thisArea = (j - i) * Math.Min(height[i], height[j]);                res = Math.Max(res, thisArea);            }        }        return res;    }

第二种解法:双指针(左指针大于右指针,left++)

public int MaxArea(int[] height)    {        int res = 0;        int left = 0; int right = height.Length - 1;        while (left < right)        {            int thisArea = (right - left) * Math.Min(height[left], height[right]);            res = Math.Max(res, thisArea);            if (height[left] > height[right]) right--;            else left++;        }        return res;     }

第三种解法:双指针优化(左指针小于等于最小高度,left++)

public int MaxArea(int[] height)    {        int res = 0;        int left = 0; int right = height.Length - 1;        while (left < right)        {            int minHeight = Math.Min(height[left], height[right]);            int thisArea = (right - left) * minHeight;            res = Math.Max(res, thisArea);            if (left < right && height[left] <= minHeight) left++;            if (left < right && height[right] <= minHeight) right--;        }        return res;    }

结果:

源码地址:https://github.com/amusement1234/LeetCode_CSharp

转载地址:http://khzdi.baihongyu.com/

你可能感兴趣的文章
【分布式存储】CAP、BASE与ACID原则
查看>>
Mybatis if test中字符串比较
查看>>
【基础篇】Java常见的runtime exception
查看>>
ehcache、memcache、redis三大缓存比较
查看>>
缓存穿透、缓存击穿、缓存雪崩概念及解决方案
查看>>
Error:No converter found for return value of type
查看>>
请自觉收藏,Linux常用基本命令
查看>>
mysql常见存储引擎简介
查看>>
Redis的持久化机制,你了解吗
查看>>
微视linux 根文件系统之二 bootloader(以uboot为例)的准备
查看>>
微视linux 根文件系统之三 内核解压缩
查看>>
数据结构与算法之图的DFS算法
查看>>
数据结构与算法 递归的理解
查看>>
微视linux 通用块层之bio
查看>>
微视linux 进程的当前目录
查看>>
慢慢欣赏linux 页面回收续
查看>>
微视linux内核 x86_32内核启动
查看>>
链接脚本
查看>>
微视linux 内存水线划分
查看>>
微视linux 文件系统之打开文件返回只读
查看>>