您的位置:首页 > 大数据 > 人工智能

【leetcode】Container With Most Water

2015-02-06 14:08 344 查看

题目描述:

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.

解题思路:

这道题说白了就是选两个值中较小的一个\(min(a_i,a_j)\),然后乘以他们之间的间距\((i-j)\)的最大值.最简单的\(O(n^2)\)的遍历。但是我们可以采取贪心的算法,从两端开始不断选择较大的一侧组成新的container。

class Solution:
# @return an integer
def maxArea(self, height):
res = 0
l = len(height)
i = 0
j = l-1
while i < j:
t = min(height[i], height[j]) * (j-i)
if t > res:
res = t
if height[i] < height[j]:
i += 1
else:
j -= 1
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: