文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
**解析:**Version 1,通过up
和down
分别表示山脉的上下过程,比较数组前后两个数,如果相等,直接返回False
,如果前者大于后者,没出现过下山down=False
,则将上山设为up=True
,如果前者小于后者,出现了上山up=False
,则将下山设为down=True
,不符合上述条件的都直接返回False
,最后如果上山下山都出现了,则返回True
,否则返回False
。Version 2使用双指针分别从左右两侧移动,最后判断两个指针是否满足山脉条件,不满足返回False
,满足返回True
。
- Version 1
class Solution:def validMountainArray(self, arr: List[int]) -> bool:n = len(arr)up = Falsedown = Falsefor i in range(n - 1):if arr[i+1] == arr[i]:return Falseelif arr[i+1] > arr[i]:up = Trueif down:return Falseelse:if not up:return Falsedown = Trueif up and down:return Truereturn False
- Version 2
class Solution:def validMountainArray(self, arr: List[int]) -> bool:n = len(arr)if n < 3:return Falsei = 1j = n - 2while i < n and arr[i] > arr[i-1]:i += 1i -= 1while j > -1 and arr[j] > arr[j+1]:j -= 1j += 1if i == 0 or j == n - 1 or i != j:return Falsereturn True
Reference
- https://leetcode.com/problems/valid-mountain-array/