Container With Most Water

这道题是对撞指针的经典题,从题目分析可以得知决定装水多少的是短的那块板,如果我们一左一右两个指针从两边对撞,每次相对小的那一块板往中间移,则可以保证我们每次考察的都是当前位置的最大量,因为短板旁边的板如果更高,则这种情况就是我们接下去要对比的,如果比现在的板矮,则无论如何装水量都不可能有现在高,下面是代码

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        n = len(height)
        res = 0
        start, end = 0, n - 1
        while start < end:
            if height[start] < height[end]:
                res = max(res, height[start] * (end - start))
                start += 1
            else:
                res = max(res, height[end] * (end - start))
                end -= 1

        return res

results matching ""

    No results matching ""