LeetCode Container With Most Water
2015-12-17 14:16
471 查看
LeetCode解题之Container With Most Water
原题
给定一组长短不一的隔板,挑其中的两块板,使得板子之间能装最多的水。注意点:
两块板之间能装多少水是由短的那块板决定的
选定两块板之后,它们之间的板就不存在了
例子:
输入: height=[1,1,1]
输出: 2
解题思路
我们把两块板分为左板、右板,现在考虑如下情况。假设左板高度为h,且比右板低,两块板之间的距离为w,则此时最多能装水w*h,此时我们尝试移动隔板。如果将左板向右移,那么有可能使容积变大,例如,左板右边的板子高h1(还是比右板低),此时最多装水(w-1)*h1,有可能比w*h大;如果将右板向左移,由于水的高度不能高于左板,所以容积最多为(w-1)*h,肯定比w*h小。基于上面的假设,我们只要把两块隔板依次向中间靠拢,就可以求出最大的容积。AC源码
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ if not height: return 0 left = 0 right = len(height) - 1 result = 0 while left < right: if height[left] < height[right]: area = height[left] * (right - left) result = max(result, area) left += 1 else: area = height[right] * (right - left) result = max(result, area) right -= 1 return result if __name__ == "__main__": assert Solution().maxArea([1, 1]) == 1
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法