DAY6:leetcode #11 Container With Most Water
2016-04-26 10:12
531 查看
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.
一开始用了两层循环遍历的思路,超时。看到了这样的思路:采用两个指针l和r,初始化分别指向数组的两端,然后在向中间移动找到最大容量。如果l指向的数字小,则l需要右移才有可能获得更大容量,因为此时如果左移r,得到的容量肯定比左移r之前的容量小(高度已经被较小的l限制住了)。如果r指向的数字小,则需要左移r。这样,当l和r相遇的时候,最大的容量就是我们需要的。
..., 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.
一开始用了两层循环遍历的思路,超时。看到了这样的思路:采用两个指针l和r,初始化分别指向数组的两端,然后在向中间移动找到最大容量。如果l指向的数字小,则l需要右移才有可能获得更大容量,因为此时如果左移r,得到的容量肯定比左移r之前的容量小(高度已经被较小的l限制住了)。如果r指向的数字小,则需要左移r。这样,当l和r相遇的时候,最大的容量就是我们需要的。
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ max_v = 0 i = 0 j = len(height) - 1 while True: if max_v < (j-i)*min(height[i],height[j]): max_v = (j-i)*min(height[i],height[j]) if height[i] < height[j]: i += 1 else: j -= 1 if i == j: break return max_v
相关文章推荐
- linker command failed with exit code 1 (use -v to see invocation)错误调试
- cpu_relax( )-----对自选循环等待(spin-wait loops)操作的优化【转】
- mac os 终端提示 you have new mail
- 人工智能对战游戏程序会怎样?奥创大战贾维斯吗!
- UVA 818 Cutting Chains
- postmain 导致浏览器两次请求
- LintCode: Paint House II
- (整理)IIS 7 503 "service unavailable" errors
- AD的一些信息
- paintEvent调用时机
- LogCat里的错误提示 FATAL EXCEPTION: main
- LintCode:Paint House
- HDU 2476 String painter 区间dp
- 概率图模型
- bnu 51641 Certain Maze(bfs)(北师16校赛)
- caption标签,为表格添加标题和摘要 summary a mail
- bnu 51638 Air Hockey(三分+二分)(北师16校赛)
- hdu1302The Snail
- bnu 51640 Training Plan(类似区间dp)(北师16校赛)
- HDU 1023 Train ProblemII