leetcode
来源:互联网 发布:淘宝退货邮费谁承担 编辑:程序博客网 时间:2024/06/05 18:20
Question 11 —Container With Most Water
给定n个非负int型数,a1,a2, … ,an, 分别代表平面坐标系上的一个点(i,ai)。找出其中两个点,分别与对应的点(i,0)形成两条x的垂线段,并使这两条线段与x轴形成的容器盛水最多。
思路
下文中使用字母及其意义:Maxv(最大体积),Se(较短边),D(两边间的距离)
首先明确: 两条线与x轴围成的容器,Maxv=Se*D(水超过短边时就会流出)
当两边间的距离最大时,即取首尾两条边时,以这个体积为标准Vs。此时,无论你去取其他任意两条边,边间的距离都要比这个Vs的小,所以在D变小的情况下,想要Maxv达到最大,只能增大Se。
算法
用两个flag分别标记(或指针指向)该列数的首尾。并不断移动短边的flag(使Se增大),使其指向短边的下一条边(对于后面的则是前一条边)。每次算一次体积,并取其中最大的。
Code
int maxArea(vector<int>& height) { int nums=height.size(); int max=0; int start=0; int end=nums-1; while(start!=end){ int nowarea=(end-start)*(height[start]>height[end]?height[end--]:height[start++]); max=(max<nowarea?nowarea:max); } return max; }
时间复杂度
很明显O(n)
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Android shape属性详解(自定义图片和形状)
- 利用java反射实现任意数组copy,reflect.Array
- Solr(一)——搭建solr全文搜索服务
- 这是一篇正经的博文
- dynamodb:tried to access class com.amazonaws.services.dynamodbv2.document.internal.IteratorSupport
- leetcode
- 将博客搬至CSDN
- 2017 ACM-ICPC 亚洲区(西安赛区)网络赛 F. Trig Function(切比雪夫定理)
- DB2 系统命令与配置参数大全
- hive官方文档翻译
- HTML的补充,HTML框架
- 第二周——项目二—程序的多文件组织
- 数据库锁机制
- 面试题总结