239. 滑动窗口最大值
单调队列:单调递减,一个queue,最大值在queue口,队列中只维护有可能为最大值的数字
比如说1,3,2,4;当sliding window已经到3时,就可以把1 pop出去了,因为有了3,1不可能为最大值,同理到4的时候,3、2都可以pop出去
class MyQueue:
def __init__(self):
self.queue = deque()
def pop(self, value):
if self.queue and value == self.queue[0]:
self.queue.popleft()
def push(self, value):
while self.queue and value > self.queue[-1]:
self.queue.pop()
self.queue.append(value)
def front(self):
return self.queue[0]
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
q = MyQueue()
result = []
for i in range(k):
q.push(nums[i])
result.append(q.front())
for i in range(k, len(nums)):
q.pop(nums[i-k])
q.push(nums[i])
result.append(q.front())
return result
347.前 K 个高频元素
先把数字和频率存进一个dictionary {key数字:value出现的次数}
大顶堆:root为最大数的tree
小顶堆:root为最小数的tree
如果找前k个最大的数,应该使用小顶堆,因为一般tree pop的都是root,用小顶堆的话,正好pop的就是最小值
import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
map_ = {}
priority_q = []
for i in range(len(nums)):
if nums[i] in map_:
map_[nums[i]] += 1
else:
map_[nums[i]] = 0
for key, freq in map_.items():
heapq.heappush(priority_q, (freq, key))
if len(priority_q) > k:
heapq.heappop(priority_q)
result = [0] * k
for i in range(k-1, -1, -1):
result[i] = heapq.heappop(priority_q)[1]
return result
标签:13,nums,self,随想录,pop,queue,347,result,def
From: https://www.cnblogs.com/miramira/p/18108005