[Leetcode] 845. 数组中的最长山脉

题目链接:https://leetcode-cn.com/problems/longest-mountain-in-array/
分析:
遍历数组。先找左边界,在左边界存在的条件下,更新右边界。相等时,索引+1,否则会死循环。当左右边界都存在时,更新最大长度。
Python

class Solution:
    def longestMountain(self, A: List[int]) -> int:
        left , right = -1, -1
        i = 0 
        length = len(A)
        res = 0
        while i < length - 1:
            while i<=length-2 and A[i] == A[i+1]:
                i += 1
            while i<=length-2 and A[i] < A[i+1]:
                if left == -1:
                    left = i
                i += 1

            while i<=length-2 and A[i] > A[i+1]:
                if left != -1:
                    right = i+1
                i += 1
            if left!=-1 and right!=-1:
                res = max(res, right-left+1);
            left, right = -1, -1
        return res
posted @ 2020-10-25 12:14  我的小叮当  阅读(141)  评论(0编辑  收藏  举报