Feburary——1438. 绝对差不超过限制的最长连续子数组(滑动窗口)

class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:

        
        #利用第三方库,将列表有序化,底层其实是一个最小堆
        from sortedcontainers import SortedList
        left, right = 0, 0
        size = len(nums)
        s = SortedList()
        res = 1
        while right<size:
            s.add(nums[right])
            while s[-1]-s[0]>limit:
                s.remove(nums[left])
                left+=1
            
            res = max(res,right-left+1)
            right+=1
        return res



        #超出时间限制
        res = 1
        left,right = 0,0
        size = len(nums)
        win = deque()
        Max,Min = float('-inf'),float('inf')
        while right<size:
            
            win.append(nums[right])
            Max = max(Max,nums[right])
            Min = min(Min,nums[right])

            while Max-Min>limit:
                win.popleft()
                Max = max(win)
                Min = min(win)
            res = max(res,len(win))
            right+=1
        return res
#官方解答,还可以利用两个单调队列去维护最大值和最小值
        n = len(nums)
        queMax, queMin = deque(), deque()
        left = right = ret = 0

        while right < n:
            while queMax and queMax[-1] < nums[right]:
                queMax.pop()
            while queMin and queMin[-1] > nums[right]:
                queMin.pop()
            
            queMax.append(nums[right])
            queMin.append(nums[right])

            while queMax and queMin and queMax[0] - queMin[0] > limit:
                if nums[left] == queMin[0]:
                    queMin.popleft()
                if nums[left] == queMax[0]:
                    queMax.popleft()
                left += 1
            
            ret = max(ret, right - left + 1)
            right += 1
        
        return ret
  • 题目的本质就是需要维护一个窗口中最大值和最小值,最大值和最小值的差不超过limit即可
  • 利用python第三方库去解决这个问题,不管每次添加或者删除元素之和这个列表仍然是有序的
  • 这个库还有三个
    •  from sortedcontainers import SortedList
    • from sortedcontainers import SortedDict
    • from sortedcontainers import SortedSet

猜你喜欢

转载自blog.csdn.net/weixin_37724529/article/details/113943672