版权声明:本文为博主原创文章,未经允许,不得转载,如需转载请注明出处 https://blog.csdn.net/ssjdoudou/article/details/83351442
写在最前面:不得不说,python对于数据结构的处理非常自然,几乎就是你怎么想的直接写出来就可以,不用太过在意转化,代价就是,性能较差
leetcode【845】Longest Mounta in Array
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
- There exists some
0 < i < B.length - 1
such thatB[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A
of integers, return the length of the longest mountain.
Return 0
if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
简而言之就是对一个数组,找出长度最大的类似山峰的子数组
对于这道题的思路就是,比较A[i]两边的大小,向左,向右,然后分别统计两侧的值,加起来
class Solution:
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
length = len(A)
top = 0
for i in range(1, length):
xleft = 0
xright = 0
left = i - 1
right = i + 1
k = A[i]
while left >= 0 and A[left] < k:
k = A[left]
left -= 1
xleft += 1
k = A[i]
while right <= length - 1 and A[right] < k:
k = A[right]
right += 1
xright += 1
if xleft >= 1 and xright >= 1:
top = max(top, xright + xleft + 1)
return top
怎么说呢,leetcode没过,因为超时了,超时的用例实在有点恐怖,相同的java写的是过了的,有时间会想想怎么优化好一点
抛砖引玉吧,如果有更好的思路欢迎私我~