day10 225、232
# 225.队列实现栈
# 使用队列实现栈的下列操作:
# push(x) -- 元素 x 入栈
# pop() -- 移除栈顶元素
# top() -- 获取栈顶元素
# empty() -- 返回栈是否为空
# 时间复杂度: push为O(n),其他为O(1)
# 空间复杂度: O(n)
from collections import deque
class MyStack:
def __init__(self):
"""
Python普通的Queue或SimpleQueue没有类似于peek的功能
也无法用索引访问,在实现top的时候较为困难。
用list可以,但是在使用pop(0)的时候时间复杂度为O(n)
因此这里使用双向队列,我们保证只执行popleft()和append(),因为deque可以用索引访问,可以实现和peek相似的功能
in - 存所有数据
out - 仅在pop的时候会用到
"""
self.queue_in = deque()
self.queue_out = deque()
def push(self, x: int) -> None:
"""
直接append即可
"""
self.queue_in.append(x)
def pop(self) -> int:
"""
1. 首先确认不空
2. 因为队列的特殊性,FIFO,所以我们只有在pop()的时候才会使用queue_out
3. 先把queue_in中的所有元素(除了最后一个),依次出列放进queue_out
4. 交换in和out,此时out里只有一个元素
5. 把out中的pop出来,即是原队列的最后一个
tip:这不能像栈实现队列一样,因为另一个queue也是FIFO,如果执行pop()它不能像
stack一样从另一个pop(),所以干脆in只用来存数据,pop()的时候两个进行交换
"""
if self.empty():
return None
for i in range(len(self.queue_in) - 1):
self.queue_out.append(self.queue_in.popleft())
self.queue_in, self.queue_out = self.queue_out, self.queue_in # 交换in和out,这也是为啥in只用来存
return self.queue_out.popleft()
def top(self) -> int:
"""
1. 首先确认不空
2. 我们仅有in会存放数据,所以返回第一个即可
"""
if self.empty():
return None
return self.queue_in[-1]
def empty(self) -> bool:
"""
因为只有in存了数据,只要判断in是不是有数即可
"""
return len(self.queue_in) == 0
from collections import deque
class MyStack2:
def __init__(self):
self.que = deque()
def push(self, x: int) -> None:
self.que.append(x)
def pop(self) -> int:
if self.empty():
return None
for i in range(len(self.que)-1):
self.que.append(self.que.popleft())
return self.que.popleft()
def top(self) -> int:
if self.empty():
return None
return self.que[-1]
def empty(self) -> bool:
return not self.que
# 232. 栈实现队列
# 使用栈实现队列的下列操作:
# push(x) -- 将一个元素放入队列的尾部。
# pop() -- 从队列首部移除元素。
# peek() -- 返回队列首部的元素。
# empty() -- 返回队列是否为空。
# 时间复杂度: push和empty为O(1), pop和peek为O(n)
# 空间复杂度: O(n
class MyQueue:
def __init__(self):
"""
in主要负责push,out主要负责pop
"""
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
"""
将一个元素放入队列的尾部。
有新元素进来,就往in里面push
"""
self.stack_in.append(x)
def pop(self) -> int:
"""
从队列前面移除元素并返回该元素
Removes the element from in front of queue and returns that element.
"""
if self.empty():
return None
if self.stack_out:
return self.stack_out.pop()
else:
for i in range(len(self.stack_in)):
self.stack_out.append(self.stack_in.pop())
return self.stack_out.pop()
def peek(self) -> int:
"""
Get the front element.
"""
ans = self.pop()
self.stack_out.append(ans)
return ans
def empty(self) -> bool:
"""
只要in或者out有元素,说明队列不为空
"""
return not (self.stack_in or self.stack_out)
day11 20、150、1047
# 20 有效的括号
# 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
#
# 有效字符串需满足:
# 左括号必须用相同类型的右括号闭合。
# 左括号必须以正确的顺序闭合。
# 注意空字符串可被认为是有效字符串。
# 方法一,仅使用栈,更省空间
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for item in s:
if item == '(':
stack.append(')')
elif item == '[':
stack.append(']')
elif item == '{':
stack.append('}')
elif not stack or stack[-1] != item:
return False
else:
stack.pop()
return True if not stack else False
# 150、逆波兰表达式
# 根据 逆波兰表示法,求表达式的值。
#
# 有效的运算符包括 + , - , * , / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
#
# 说明:
#
# 整数除法只保留整数部分。 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
from operator import add, sub, mul
class Solution:
op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}
def evalRPN(self, tokens) -> int:
stack = []
for token in tokens:#遇见非操作符,数字加入栈
if token not in {'+', '-', '*', '/'}:
stack.append(int(token))
else:#遇见操作符,取出两个数字,将梳子操作符计算结果加入栈
op2 = stack.pop()
op1 = stack.pop()
stack.append(self.op_map[token](op1, op2)) # 第一个出来的在运算符后面
return stack.pop()
# 给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
# 在 S 上反复执行重复项删除操作,直到无法继续删除。
# 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
# 时间复杂度: O(n)
# 空间复杂度: O(1),返回值不计空间复杂度
# 方法一,使用栈
class Solution:
def removeDuplicates(self, s: str) -> str:
res = list()
for item in s:
# res中有值,且当前item与res最后一个值同
if res and res[-1] == item:
# 删除res栈顶值
res.pop()
else:
res.append(item)
return "".join(res) # 字符串拼接
day13 239、347
#
# 给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
#
# 返回滑动窗口中的最大值
# class MyQueue {
# public:
# void pop(int value) {
# }
# void push(int value) {
# }
# int front() {
# return que.front();
# }
# };
# 设计单调队列的时候,pop,和push操作要保持如下规则:
#
# pop(value):如果窗口移除的元素value等于单调队列的出口元素,
# 那么队列弹出元素,否则不用任何操作
# push(value):如果push的元素value大于入口元素的数值,
# 那么就将队列入口的元素弹出,直到push元素的数值小于等于队列入口元素的数值为止
# 时间复杂度: O(n)
# 空间复杂度: O(k)
from collections import deque
class MyQueue: # 单调队列(从大到小
def __init__(self):
self.queue = deque() # 这里需要使用deque实现单调队列,直接使用list会超时
# 每次弹出的时候,比较当前要弹出的数值是否等于队列出口元素的数值,如果相等则弹出。
# 同时pop之前判断队列当前是否为空。
def pop(self, value):
if self.queue and value == self.queue[0]:
self.queue.popleft() # list.pop()时间复杂度为O(n),这里需要使用collections.deque()
# 如果push的数值大于入口元素的数值,那么就将队列后端的数值弹出,直到push的数值小于等于队列入口元素的数值为止。
# 这样就保持了队列里的数值是单调从大到小的了。
def push(self, value):
while self.queue and value > self.queue[-1]:
self.queue.pop()
self.queue.append(value)
# 查询当前队列里的最大值 直接返回队列前端也就是front就可以了。
def front(self):
return self.queue[0]
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
que = MyQueue()
result = []
for i in range(k): # 先将前k的元素放进队列
que.push(nums[i])
result.append(que.front()) # result 记录前k的元素的最大值
for i in range(k, len(nums)):
que.pop(nums[i - k]) # 滑动窗口移除最前面元素
que.push(nums[i]) # 滑动窗口前加入最后面的元素
result.append(que.front()) # 记录对应的最大值
return result
# 1. heapify(x) : 将列表x转换为堆(小根堆)。
# 2. heappush(heap,item): 将item压入堆中。(heap使存放堆的数组)
# 3. heappop(heap): 从堆中弹出最小的项,并将其值返回。
import heapq
class Solution:
def topKFrequent(self, nums, k: int) :
# 要统计元素出现频率
map_ = {} # nums[i]:对应出现的次数
for i in range(len(nums)):
map_[nums[i]] = map_.get(nums[i], 0) + 1
# 对频率排序
# 定义一个小顶堆,大小为k
pri_que = [] # 小顶堆
# 用固定大小为k的小顶堆,扫描所有频率的数值
for key, freq in map_.items():
heapq.heappush(pri_que, (freq, key))
if len(pri_que) > k: # 如果堆的大小大于了K,则队列弹出,保证堆的大小一直为k
heapq.heappop(pri_que)
# 找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒序来输出到数组
result = [0] * k
for i in range(k - 1, -1, -1):
result[i] = heapq.heappop(pri_que)[1]
return result