C#LeetCode刷题之#11-盛最多水的容器(Container With Most Water)
问题
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3615 访问。
给定 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
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.
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
示例
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3615 访问。
public class Program {
public static void Main(string[] args) {
var height = new int[] { 1, 8, 6, 2, 5, 4, 8, 3, 7 };
var res = MaxArea(height);
Console.WriteLine(res);
height = new int[] { 5, 7, 2, 0, 9, 1, 5, 16, 25, 36 };
res = MaxArea2(height);
Console.WriteLine(res);
Console.ReadKey();
}
public static int MaxArea(int[] height) {
//暴力法
var max = 0;
for(var i = 0; i < height.Length; i++) {
for(var j = i + 1; j < height.Length; j++) {
max = Math.Max(max, Math.Min(height[i], height[j]) * (j - i));
}
}
return max;
}
public static int MaxArea2(int[] height) {
//双指针法
var max = 0;
var left = 0;
var right = height.Length - 1;
while(left < right) {
max = Math.Max(max, Math.Min(height[left], height[right]) * (right - left));
//“木桶”左右板短的那边向中心移动
if(height[left] < height[right]) left++;
else right--;
}
return max;
}
}
以上给出2种算法实现,以下是这个案例的输出结果:
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3615 访问。
49
56
分析:
显而易见,MaxArea 的时间复杂度为: ,MaxArea2 的时间复杂度为: 。
最新文章
- Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:]
- 在Eclipse中生成接口的JUnit测试类
- 清除Cookie、获取指定Cookie的值、添加一个Cookie(24小时过期)、添加一个Cookie
- 完整的 AJAX 写法(支持多浏览器)
- iOS子线程操作UI问题检查
- eclipse开发工具Import工程后,工程文件夹上出现黄色感叹号——解决方法
- vs2013安装visual assist和viemu之后提示功能等无效解决
- linux中的权限
- js--DOM&;BOM总结思维导图---2017-03-24
- SQL*Plus工具
- Java课程寒假之开发记账本软件(网页版)之一
- 实验五:Xen环境下多虚拟机的桥接配置
- LODOP弹出对话框获取保存文件的路径
- Hadoop概念学习系列之Hadoop集群动态增加新节点或删除已有某节点及复制策略导向 (四十三)
- 负载均衡下 tomcat session 共享
- scrapy 抓取拉勾网数据
- Hadoop HBase概念学习系列之HBase里的长表VS宽表VS窄表(十五)
- mycat结合双主复制实现读写分离模式
- With Visual Studio, Open Same File In Two Windows, Updates Reflected in Both
- Go基础---->;go的基础学习(一)
热门文章
- 怎样从gitHub上面拉项目
- echarts 踩坑 : 为什么触摸柱状图的时后柱子不见了?原来是color的锅!
- echarts 实战 : 恼人的间隔问题
- Java 线程与同步的性能优化
- Java中hashCode方法的理解以及此小结的总结练习(代码)
- C# POST请求中raw 参数的传递
- spring学习(四)使用注解代替xml配置
- 面试题三十:包含min函数的栈
- ANDROID自定义视图——onMeasure,MeasureSpec源码&#160;流程&#160;思路详解
- java基础(11)--封装