目录
Leetcode115:最小栈||剑指30:包含min函数的栈
Leetcode295||剑指41:数据流中的中位数(题解参考)
Leetcode946:验证栈序列||剑指31:栈的压入、弹出序列(题解参考)
1. 数组实现栈
基本思路:1. 初始化;2. 判断是否为空;3. 获取栈的长度;4. 获取栈顶元素;5. 压栈push;6. 弹栈pop;
class myStack(object):
def __init__(self):
self.stack = []
# 判断栈是否为空
def is_empty(self):
return len(self.stack) == 0
# 获取栈中元素个数
def get_size(self):
return len(self.stack)
# 返回栈顶元素
def get_top(self):
if self.is_empty():
return None
else:
return self.stack[-1]
# 压栈
def push(self, item):
self.stack.append(item)
# 弹栈
def pop(self):
if self.is_empty():
return None
else:
return self.stack.pop()
2. 两个队列queue实现一个栈stack(题解参考)
基本思路:将queue1中的元素全部pop到queue2中,只留下最后一个;交换queue1 and queue2位置,再将此时queue2(换位之前是queue1)中仅剩的一个元素pop出去;
class myStack:
def __init__(self):
self.queue1 = []
self.queue2 = []
def push(self, item):
self.queue1.append(item)
def pop(self):
if not self.queue1:
return None
while len(self.queue1) != 1:
self.queue2.append(self.queue1.pop(0))
self.queue1, self.queue2 = self.queue2, self.queue1 # 交换是为了下一次的pop(0)
return self.queue2.pop(0)
3. 两个栈stack实现一个队列queue
class CQueue(object):
def __init__(self):
self.a = []
self.b = []
def appendTail(self, value):
"""
:type value: int
:rtype: None
"""
self.a.append(value)
def deleteHead(self):
"""
:rtype: int
"""
if self.b: return self.b.pop()
elif not self.a: return -1
else:
while self.a:
self.b.append(self.a.pop())
return self.b.pop()
4. 两个栈实现排序
基本思路:维护一个递减的辅助栈;
if cur <= 【help 的栈顶元素】,cur 压入help栈中;
else cur > 【help 的栈顶元素】,逐一弹出help, 直到cur <= 【help 的栈顶元素】,在将cur压入help;
"""
维护一个最小递减的辅助栈
"""
def sortByStack(stack):
helpStack = []
while stack:
cur = stack.pop()
while helpStack and cur > helpStack[-1]:
stack.append(helpStack.pop())
helpStack.append(cur)
while helpStack:
stack.append(helpStack.pop())
Leetcode115:最小栈||剑指30:包含min函数的栈
题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
基本思路:维护一个递减的辅助栈(栈顶元素即为最小值);
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stackA = []
self.stackB = [] # 辅助栈(递减,栈顶即为最小值)
def push(self, x: int) -> None:
self.stackA.append(x)
if not self.stackB or x <= self.stackB[-1]:
self.stackB.append(x)
def pop(self) -> None:
if not self.stackA: return None
item = self.stackA.pop()
if item == self.stackB[-1]:
self.stackB.pop()
def top(self) -> int:
if not self.stackA:
return -1
return self.stackA[-1]
def getMin(self) -> int:
if not self.stackB: return -1
return self.stackB[-1]
Leetcode739:每日温度(题解参考)
题目:根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。来源:力扣(LeetCode)
示例:例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]
基本思路:利用递减的栈结构
class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
size = len(T)
ans = [0] * size
stack = []
for i in range(size):
if not stack or T[i] <= T[stack[-1]]:
stack.append(i)
else:
while stack and T[i] > T[stack[-1]]:
ans[stack[-1]] = i - stack[-1]
stack.pop()
stack.append(i)
return ans
Leetcode295||剑指41:数据流中的中位数(题解参考)
题目:如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
基本思路:左半部分维护一个最大堆,右半部分维护一个最小堆;<heapq默认是最小堆,只要将所有的pop and push操作取反即可>
from heapq import *
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.lo = []
self.hi = []
def addNum(self, num: int) -> None:
if len(self.lo) != len(self.hi):
heappush(self.hi, num)
heappush(self.lo, -heappop(self.hi))
else:
heappush(self.lo, -num)
heappush(self.hi, -heappop(self.lo))
def findMedian(self) -> float:
return self.hi[0] if len(self.hi) != len(self.lo) else (self.hi[0] - self.lo[0]) / 2.0
# 以下方式是错误的方式,不能pop出来,改变结构了,取中位数应该是取当前状态
# return heappop(self.hi) if len(self.lo) != len(self.hi) else ((heappop(self.hi) - heappop(self.lo)) / 2.0)
Leetcode946:验证栈序列||剑指31:栈的压入、弹出序列(题解参考)
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
基本思路:辅助栈模拟push and pop操作;
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack = []
i = 0
for item in pushed:
stack.append(item)
while stack and stack[-1] == popped[i]:
stack.pop()
i += 1
return True if not stack else False