You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
def is_mountain_array(array):
max_item = array[0]
if len(array) < 3:
return False
# 1. 找出最大元素
for i in range(len(array)):
if array[i] > max_item:
max_item = array[i]
if max_item in [array[0], array[-1]]:
return False
item_index = array.index(max_item)
# 每个元素是否满足规则
is_ok = []
for i in range(len(array)-1):
if i < item_index:
# 左边元素
if array[i] < array[i+1]:
is_ok.append(True)
else:
is_ok.append(False)
continue
# 右边元素
if i >= item_index:
if array[i] > array[i+1]:
is_ok.append(True)
else:
is_ok.append(False)
continue
if False in is_ok:
return False
else:
return True
if __name__ == '__main__':
print(is_mountain_array([1, 2, 3, 3, 1]))
Activity
zhangke666163 commentedon Jul 29, 2021
思路:
时间、空间复杂度:O(n)
代码:
xuezc1119 commentedon Jul 29, 2021
思路
递增判断并获取到目前为止的最大值
最大值后半段递减判断
第一个和最后一个都不能是最大值
复杂度
时间复杂度O(n),空间复杂度O(1)
代码
lyonyang commentedon Aug 7, 2021
思路一 - 标志判断
定义一个标志位 , 标志是处于上升阶段还是下降阶段
注意 : 标志位最终结果必须标志着下降才是有效的山脉数组
时间复杂度:$O(N)$ ,
N为数组长度空间复杂度:$O(1)$
思路二 - 双指针
利用双指针 , 分别同时从左右两边进行遍历 , 当左右指针都开始下降时停止 , 如果此时左右指针相等则为有效山脉 , 否则无效
注意 : 结束循环时 , 左指针不能是第一个元素 , 右指针不能是最后一个元素
时间复杂度:$O(N)$ ,
N为数组长度空间复杂度:$O(1)$