Container With Most Water - LeetCode
2015-04-07 20:24
288 查看
Container With Most Water - LeetCode
题目:
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.
分析:
这道题目一开始没注意note,结果一直以为两线与x轴成一个梯形。。然后想了半天没想出来,其实是组成个矩形,就是一个盛水槽,这个我们知道,槽子的高度取决于两侧高度的短板,这样我们可以用两个指针,l在开头,r在结尾,当l<r时,我们希望提高l,所以l++;同理r<l时,我们希望提高r,所以r--。每一次循环都判断此时面积是否是大于res的,如果大于替换掉res。结束条件自然是当r=l时。
代码:
class Solution: # @return an integer def maxArea(self, height): if not height: return 0 res = 0 l = 0 r = len(height)-1 while l<r: res = max(res,min(height[l],height[r])*(r-l)) if height[l]<height[r]: l += 1 else: r -= 1 return res
相关文章推荐
- Container With Most Water-Leetcode OJ Problem 11
- LeetCode Container With Most Water
- leetcode-Container With Most Water
- [LeetCode]Container With Most Water
- 11. Container With Most Water LeetCode
- leetcode--Container With Most Water
- 思维题(两点逼近)LeetCode11 Container with Most Water
- LeetCode Container With Most Water
- [leetcode]Container With Most Water
- leetcode第11题——**Container With Most Water
- LeetCode_Container With Most Water
- LeetCode Container With Most Water
- leetcode -- Container With Most Water
- LeetCode OJ Container With Most Water
- [LeetCode] Container With Most Water, Solution
- Container With Most Water (隔板如何蓄水) 【leetcode】
- Container With Most Water--LeetCode
- [LeetCode][JavaScript]Container With Most Water
- [LeetCode] Container With Most Water
- LeetCode——Container With Most Water