题目
我们把数组 A 中符合下列属性的任意连续子数组 B 称为 “山脉”:
B.length >= 3
存在 0 < i < B.length - 1 使得 B[0] < B[1] < … B[i-1] < B[i] > B[i+1] > … > B[B.length - 1]
(注意:B 可以是 A 的任意子数组,包括整个数组 A。)
给出一个整数数组 A,返回最长 “山脉” 的长度。
如果不含有 “山脉” 则返回 0。
示例 1:
输入:[2,1,4,7,3,2,5]
输出:5
解释:最长的 “山脉” 是 [1,4,7,3,2],长度为 5。
示例 2:
输入:[2,2,2]
输出:0
解释:不含 “山脉”。
提示:
0 <= A.length <= 10000
0 <= A[i] <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-mountain-in-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
这题本来想的直接笨写就好了,结果变量越加越多。。。。
遇到的问题
无
代码
class Solution:
def longestMountain(self, A: List[int]) -> int:
left=0
right=0
maxlen=0
templeftcount=0
tempcount=0
if(not len(A)):
return 0
lastone=A[0]
for i in range(1,len(A)):
if(A[i]>lastone):
tempcount=0
templeftcount=0
left=left+1
right=0
elif(A[i]==lastone):
left=0
right=0
else:
if left>0:
templeftcount=left
tempcount=left+1
left=0
if templeftcount>0:
tempcount=tempcount+1
maxlen=max(maxlen,tempcount)
lastone=A[i]
if maxlen==0:
return 0
else:
return maxlen
结果
通过 200 ms 14.8 MB
结论
还是太菜