其他分享
首页 > 其他分享> > 941. 有效的山脉数组

941. 有效的山脉数组

作者:互联网

给定一个整数数组 A,如果它是有效的山脉数组就返回 true,否则返回 false

让我们回顾一下,如果 A 满足下述条件,那么它是一个山脉数组:

示例 1:

输入:[2,1]
输出:false

示例 2:

输入:[3,5,5]
输出:false

示例 3:

输入:[0,3,2,1]
输出:true

提示:

  1. 0 <= A.length <= 10000
  2. 0 <= A[i] <= 10000 

 

class Solution:
    def validMountainArray(self, A: 'List[int]') -> 'bool':
        if len(A) < 3:
            return False
        upmountain, downmountain = False, False
        # 判断上坡
        for i in range(len(A)-1):
            if A[i] < A[i + 1]:
                upmountain = True
            else:
                break
        # 判断下坡
        for j in range(i, len(A) -1):
            if A[j] > A[j + 1]:
                downmountain = True
            else:
                downmountain = False
                break
        # 判断是否为山脉
        if j == len(A)-2 and upmountain and downmountain:
            return True
        else:
            return False

    def validMountainArray2(self, A: 'List[int]') -> 'bool':
        if len(A) < 3:
            return False
        elif A[0] >= A[1] or A[-1] >= A[-2]:
            return False
        p = A[0]
        flag = True
        for x in A[1:]:
            # 判断上坡
            if flag:
                if x > p:
                    p = x
                elif x < p:
                    flag = False
                    p = x
                else:
                    return False
            # 判断下坡
            else:
                if x < p:
                    p = x
                else:
                    return False
        return True
    #两头双指针应该也可以实现
if __name__=='__main__':
    s = Solution()
    A = [3,5,3]
    print(s.validMountainArray(A))

 

标签:__,return,len,else,数组,山脉,False,941,True
来源: https://blog.csdn.net/hushaoqiqimingxing/article/details/88650451