python 中deque 双边队列,实现使用popleft,pop,append,appendlef等函数实现对两边的操作
本题维护两个双边队列,一个递增,存放某种意义上的最小值,一个递减,存放某种意义上的最大值。
枚举每一个值,将该值放到两个队列最右边,并维护单调性
之后就可以从队列左侧开始,因为左侧的点是之前出现的点,对于递减队列,存放的是当前子序列的最大值,对于递增队列,存放的是当前子序列的最小值。之后滑动l,如果num[l]和某个值相等,那么就找到了不满足条件的点,去掉即可。本文中这种思想无需记录下标,也有记录下标的做法,大致思想也是相同的
class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
from collections import deque
#两个单调双端队列,
q1=deque()#单调递减
q2=deque()#单调递增
n = len(nums)
l = 0
res = 0
for i in range(n):
while len(q1) and nums[i]>q1[-1]:
q1.pop()
q1.append(nums[i])
while len(q2) and nums[i]<q2[-1]:
q2.pop()
q2.append(nums[i])
while q1[0] - q2[0] > limit:
if nums[l] == q1[0]:
q1.popleft()
if nums[l] == q2[0]:
q2.popleft()
l += 1
if q1[0] - q2[0] <= limit:
res = max(res, i - l +1)
return res