Leetcode 1574. Shortest Subarray to be Removed to Make Array Sorted [Python]

该博客介绍了如何利用双指针技术解决数组中找到最短非降子数组的问题。通过遍历数组,找到头部非降序列和尾部非降序列,然后比较它们之间的交叉部分,确定最短长度。博客内容涉及动态规划和数组操作,适合算法学习者阅读。

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

一开始看以为考察DP。。按照题目的意思,只有一段下降,所以使用两个指针,截取出头部开始的非下降subarray和截止于尾部的非下降subarray,随后看前者的前缀保留多少,后者的后缀保留多少个,中间的部分就是需要去掉的subarray。

class Solution:
    def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
        N = len(arr)
        head_inc = 0
        tail_inc = N-1
        
        while head_inc + 1 < N and arr[head_inc+1] >= arr[head_inc]:
            head_inc += 1
        while tail_inc - 1 >= 0 and arr[tail_inc-1] <= arr[tail_inc]:
            tail_inc -= 1
            
        res = tail_inc#make sure to use this length as initiation, in case we have [5 4 3 2 1].
        
        head_inc_seq = arr[:head_inc+1]
        tail_inc_seq = arr[tail_inc:]
        
        for startindex, num in enumerate(head_inc_seq):
            endindex = bisect.bisect_left(tail_inc_seq, num)
            res = min(tail_inc + endindex - 1 -startindex, res)
        return max(res, 0) # when the arr is 12345, 0 + 0 - 0 - 1 = -1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值