subject : Original link ( Simple )
solution
Time complexity
Spatial complexity
Execution time
Ans 1 (Python)
256ms (67.37%)
Ans 2 (Python)
252ms (76.14%)
Ans 3 (Python)
LeetCode Of Python Execution time , As long as there is no significant difference in time complexity , The execution time is generally of the same order of magnitude , For reference only .
Solution 1 ( One way traversal ):
def validMountainArray(self, A: List[int]) -> bool:
up = 0
down = 0
for i in range(len(A) - 1):
if A[i] < A[i + 1]:
if down:
return False
up += 1
elif A[i] > A[i + 1]:
down += 1
else:
return False
return up > 0 and down > 0
Solution 2 ( Bidirectional traversal ):
def validMountainArray(self, A: List[int]) -> bool:
idx1 = 0
idx2 = len(A) - 1
while idx1 < idx2:
if A[idx1] < A[idx1 + 1]:
idx1 += 1
elif A[idx2 - 1] > A[idx2]:
idx2 -= 1
else:
return False
return idx1 != 0 and idx2 != len(A) - 1