程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Leetcode problem solving (0941): valid mountain array (Python)

編輯:Python


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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.




  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved