150. 逆波兰表达式求值
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for item in tokens:
if item in {'+','-','*','/'}:
num2 = stack.pop()
num1 = stack.pop()
if item == '+':
res = num1+num2
elif item == '-':
res = num1-num2
elif item == '*':
res = num1*num2
else:
res = int(num1/num2)
stack.append(res)
else:
stack.append(int(item))
return stack.pop()
239. 滑动窗口最大值
单调队列
from collections import deque
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
monoq = MonoQueue()
max_q = []
# initialize monoq
for i in range(k):
monoq.push(nums[i])
max_q.append(monoq.front())
# slide the window
for i in range(len(nums)-k):
monoq.pop(nums[i])
monoq.push(nums[i+k])
max_q.append(monoq.front())
return max_q
class MonoQueue:
def __init__(self) -> None:
self.queue = deque()
def push(self, val: int) -> None:
while self.queue and self.queue[-1] < val:
self.queue.pop()
self.queue.append(val)
def pop(self, val: int) -> int:
if self.queue[0] == val:
return self.queue.popleft()
else:
return
def front(self) -> int:
return self.queue[0]
347.前 K 个高频元素
优先级队列:大顶堆/小顶堆
import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# get the frequency
map_ = defaultdict(int)
for num in nums:
map_[num] += 1
# construct a heaq to sort the frequency
pri_que = []
for key, value in map_.items():
heapq.heappush(pri_que,(value, key)) # add pair(value, key) and sort the heap according to value
if len(pri_que)>k:
heapq.heappop(pri_que)
res = []
for value, key in pri_que:
res.append(key)
return res