Feburary-1438. The longest continuous sub-array whose absolute difference does not exceed the limit (sliding window)

 

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

 

  • The essence of the problem is to maintain the maximum and minimum values ​​in a window, and the difference between the maximum and minimum values ​​does not exceed limit.
  • Use python third-party libraries to solve this problem, no matter the sum of elements is added or deleted each time, the list is still in order
  • There are three more in this library
    •  from sortedcontainers import SortedList
    • from sortedcontainers import SortedDict
    • from sortedcontainers import SortedSet

 

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/113943672