【LeetCode】11. 盛最多水的容器

class Solution:
    def maxArea(self, height: List[int]) -> int:   
        # 问题的本质,就是(i-j)*min(List[i],List[j])
        # 如果移动长板,那么面积就一定会减小
        # 所以在移动的时候,一定是移动短板
        # 经典双指针问题
        LeftIndex, RightIndex, tmpEnding= 0, len(height) - 1, 0
        while LeftIndex < RightIndex:
            if height[LeftIndex] < height[RightIndex]:
                tmpEnding = max(tmpEnding, height[LeftIndex] * (RightIndex - LeftIndex))
                LeftIndex += 1
            else:
                tmpEnding = max(tmpEnding, height[RightIndex] * (RightIndex - LeftIndex))
                RightIndex -= 1
        return tmpEnding

可惜Python没有三元运算符,换用三元运算符会写的更好看些

这是一道双指针问题,从中可以学到:

Python的初始化方法->多个变量可以同时初始化

While循环在双指针中的使用

posted @ 2022-01-06 10:42  MoKin_Li  阅读(21)  评论(0编辑  收藏  举报