程序员代码面试指南 python实现(第一章 栈和队列 :最大值减去最小值小于或等于num的子数组数量)
程序员文章站
2022-07-15 16:58:41
...
程序员代码面试指南 python实现(最大值减去最小值小于或等于num的子数组数量)
最大值减去最小值小于或等于num的子数组数量
题目描述
解答
class Deque(object):
def __init__(self):
self.data = []
def isEmpty(self):
return self.data == []
def addFront(self,newElem):
self.data.insert(0,newElem)
def addRear(self,newElem):
self.data.append(newElem)
def removeFront(self):
return self.data.pop(0)
def removeRear(self):
return self.data.pop()
def peekFront(self):
return self.data[0]
def peekRear(self):
return self.data[len(self.data)-1]
def size(self):
return len(self.data)
def getNum(arr,num):
if arr == None or len(arr) == 0:
return 0
qmin = Deque()
qmax = Deque()
i=0
j=0
res = 0
while i < len(arr):
while j < len(arr):
while qmin.isEmpty() != True and arr[qmin.peekRear()] >= arr[j]:
qmin.removeRear()
qmin.addRear(j)
while qmax.isEmpty() != True and arr[qmax.peekRear()] <= arr[j]:
qmax.removeRear()
qmax.addRear(j)
if arr[qmax.peekFront()] - arr[qmin.peekFront()] > num:
break
j=j+1
if qmin.peekFront() == i:
qmin.removeFront()
if qmax.peekFront() == i:
qmax.removeFront()
res += j-i
i += 1
return res