leetcode | 最大装水量问题 | python
2017-05-31 19:58
411 查看
问题如下:
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.
给出一个数组,每个元素表示水桶高度,水桶的最终高度由数组中的两个元素组成(由两者较小的高度决定,短板效应),水桶的宽度由两个元素的下标差决定,求最大装水量。
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i = 0
j = len(height)-1
water = 0
while i<j:
water = max(water,(j-i)*min(height[i],height[j]))
if height[i]<height[j]:
i+=1
else:
j-=1
return water其中i,j等同于数组的指针,算法的时间复杂度 O(n),每次只移动高度较小的指针。
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.
给出一个数组,每个元素表示水桶高度,水桶的最终高度由数组中的两个元素组成(由两者较小的高度决定,短板效应),水桶的宽度由两个元素的下标差决定,求最大装水量。
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i = 0
j = len(height)-1
water = 0
while i<j:
water = max(water,(j-i)*min(height[i],height[j]))
if height[i]<height[j]:
i+=1
else:
j-=1
return water其中i,j等同于数组的指针,算法的时间复杂度 O(n),每次只移动高度较小的指针。
相关文章推荐
- 连续子向量的最大和问题(Python实现)
- [LeetCode] 最大容器问题 Container with Most Water
- leetcode笔记:Maximum Subarray(最大子串和问题)
- 最大K个数问题的Python版解法总结
- [leetcode]53. Maximum Subarray 最大连续子串python实现【medium】
- 一个无聊男人的疯狂《数据结构与算法分析-C++描述》学习笔记 用C++/lua/python/bash的四重实现(3) 最大子序列和问题
- python简单解决最大子列和问题
- PAT 01-1. 最大子列和问题(20)-Python
- 计算4000000000内的最大f(n)=n值---字符串的问题python实现(五岁以下儿童)
- leetcode 计算最大盛水量
- LeetCode Container With Most Water 查找容水量最大的容器 动态规划法思想分析
- [LeetCode系列] 二叉树最大深度求解问题(C++递归解法)
- IT公司面试题--最大储水量问题
- 【LeetCode】【Python解决问题的方法】Best Time to Buy and Sell Stock II
- 求字数组最大和问题 python
- Python实现最大子树问题
- 计算4000000000以内最大的f(n)=n的值---字符串问题python实现(五)
- [leetcode]分治法求解最大子序列问题——Java实现
- [151225] Python3 实现最大堆、堆排序,解决TopK问题
- python 中最大,最小数的问题