leetcode【845】Longest Mountain in Array

本文详细解析LeetCode题目845,寻找数组中最长的山脉子数组,即连续子数组中元素先递增再递减的情况。通过遍历数组并比较相邻元素,统计最长山脉子数组的长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写在最前面:不得不说,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 that B[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:

  1. 0 <= A.length <= 10000
  2. 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写的是过了的,有时间会想想怎么优化好一点

抛砖引玉吧,如果有更好的思路欢迎私我~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值