LeetCode Array Medium 11. Container With Most Water
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: [,,,,,,,,]
Output:
题目描述:给定n(n>=2)个非负整数,构成下面的图,找到两条线,它们与x轴一起形成一个容器,这样容器就含有最多的水。
思路:可以理解为求矩形的最大面积。将y轴的点到x轴的垂直距离作为矩形的一边,两个点的x轴的值的差作为另一边。求这两个边所形成的矩形的最大面积。
两个指针分别指向给定数组的头和尾,计算面积S=(两个点的y轴的最小值)* 两个点的x轴的差值。y轴的小的点在计算之后继续向中间靠拢。直到头尾指针相邻。
代码:
//11. Container With Most Water
public int MaxArea(int[] height)
{
int maxArea = int.MinValue;
int lo = , hi = height.Length - ;
while(lo < hi)
{
int temp = ;
if(height[lo] <= height[hi])
{
temp = height[lo] * (hi - lo);
lo++;
}
else
{
temp = height[hi] * (hi - lo);
hi--;
}
if (temp > maxArea)
maxArea = temp;
}
return maxArea;
}
最新文章
- Python3.5 Day1作业:实现用户密码登录,输错三次锁定。
- 2、HDFS和Yarn的基础学习笔记
- RBAC权限设计实例
- struts2:上传多个文件时实现带进度条、进度详细信息的示范
- SignalR-入门
- 时钟 IoTimer
- linux 下载软件
- Django 同步数据库命令syncdb,makemigrations,migrate
- linux下安装pip
- wap2app(五)-- 微信授权登录以及踩过的坑
- tcp_wrapper过滤
- python 容器类型数据 (str list tuple set dict)
- Gym 101617J	Treasure Map(bfs暴力)
- 使用PerfView监测.NET程序性能(三):分组
- 安装VMware,Linux
- Spring源码分析(七)bean标签的解析及注册
- 51nod 1766 树上的最远点对 | LCA ST表 线段树 树的直径
- 如何使用mysql存储树形关系
- 小学生轻松做题App
- dojo 五 配置dojoconfig