class Solution(object):
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
# 想法:一个用来记录左边山底,一个用来记录山顶,一个用来记录右边山底
left=0
top=left
right=top
maxlength=0
while(left<len(A)-2):
length=0
# 首先找到左边山底
for i in range(left,len(A)-1):
if(A[i]<A[i+1]):
left=i
break
# 找到山顶
top=left
while(top<len(A)-1 and A[top]<A[top+1]):
top=top+1
#找到右边山底
right=top
while(right<len(A)-1 and A[right]>A[right+1]):
right=right+1
# 山脉长度
if(right>top and top>left):
length = right - left+1
left=right
else:
left=right+1
if(length>maxlength):
maxlength=length
# 但是可能存在多个山脉
return maxlength
偷懒了两天,这个代码效果不太好,明天再学习一下别人的解法,要考试了,加油复习啊,向着学弟冲啊
更简洁的写法:
class Solution(object):
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
end=base=0
length=0
while(base<len(A)-2):
end=base
if(end+1<len(A) and A[end]<A[end+1]):
while(end+1<len(A) and A[end]<A[end+1]):
end+=1 # 找到山顶,end不断向前移动
if(end+1<len(A) and A[end]>A[end+1]): # 要先判断有下山的过程
while(end+1<len(A) and A[end]>A[end+1]):
end+=1 # 找到右边山脚,end不断向前移动
length=max(length,end-base+1) # 写在有下山的条件里面
base=max(end,base+1)
return length
还有一种想法是,先找到山顶,往两边找山脚
class Solution(object):
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
length=0
for i in range(1,len(A)-1):
if(A[i]>A[i-1] and A[i]>A[i+1]):
left=i-1
right=i+1
while(left>0 and A[left]>A[left-1]):
left-=1
while(right<len(A)-1 and A[right]>A[right+1]):
right+=1
length=max(length,right-left+1)
return length
运行效率 3>2>1