[leetcode] 11. Container With Most Water @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86643731

原题

https://leetcode.com/problems/container-with-most-water/

解法

参考: 花花酱 LeetCode 11. Container With Most Water
双指针法, 水桶的面积用min(height[l], height[r])*(r-l)求得, 难点在于如何移动两个指针, 由于两个指针往中间移的时候, 宽度会降低, 我们需要找到更高的高度来求得结果, 水桶的高度是由较短的边决定的, 那么我们舍弃较短边, 如果较短边是左边, 那么左指针往右移, 寻找更大的高度, 如果较短边是右边, 那么右指针往左移.
Time: O(n/2)
Space: O(1)

代码

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        l, r = 0, len(height)-1
        res = 0
        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

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/86643731