2 Star 1 Fork 0

royce li/Leetcode_royce

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
longestSubarray.py 2.88 KB
一键复制 编辑 原始数据 按行查看 历史
Royce Li 提交于 2021-05-10 16:39 . 2020/5/10 First Commit
class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
left=right=0
maxv=minv=nums[0]
result=1
class BiQueue:
def __init__(self):
self.bigs=[]
self.smalls=[]
def push(self,val):
if not self.smalls or (self.bigs and val>=self.bigs[-1]):
i=len(self.bigs)-1
while i>=0 and val>self.bigs[i]:
self.smalls.append(self.bigs.pop())
i-=1
self.bigs.append(val)
elif not self.bigs or (self.smalls and val<self.smalls[-1]):
i=len(self.smalls)-1
while i>=0 and val<self.smalls[i]:
self.bigs.append(self.smalls.pop())
i-=1
self.smalls.append(val)
else:
self.bigs.append(val)
def remove(self,val):
if not self.bigs or val<self.bigs[-1]:
i=len(self.smalls)-1
while i>=0 and val!=self.smalls[i]:
self.bigs.append(self.smalls.pop())
i-=1
self.smalls.pop()
else:
i=len(self.bigs)-1
while i>=0 and val!=self.bigs[i]:
self.smalls.append(self.bigs.pop())
i-=1
self.bigs.pop()
def getLen(self):
if not self.bigs:
return self.smalls[-1]-self.smalls[0]
elif not self.smalls:
return self.bigs[0]-self.bigs[-1]
else:
return self.bigs[0]-self.smalls[0]
def printQueue(self):
print(self.bigs,self.smalls)
queue=BiQueue()
while right<len(nums):
queue.push(nums[right])
if queue.getLen()>limit:
if right-left>result:
result=right-left
while queue.getLen()>limit:
queue.remove(nums[left])
left+=1
right+=1
#queue.printQueue()
if right-left>result:
result=right-left
return result
'''
超时
'''
from sortedcontainers import SortedList
class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
s = SortedList()
n = len(nums)
left = right = ret = 0
while right < n:
s.add(nums[right])
while s[-1] - s[0] > limit:
s.remove(nums[left])
left += 1
ret = max(ret, right - left + 1)
right += 1
return ret
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/royce-li/leetcode_royce.git
git@gitee.com:royce-li/leetcode_royce.git
royce-li
leetcode_royce
Leetcode_royce
master

搜索帮助