225.用队列实现栈
使用队列实现栈的下列操作:
- push(x) – 元素 x 入栈
- pop() – 移除栈顶元素
- top() – 获取栈顶元素
- empty() – 返回栈是否为空
注意:
- 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is
empty 这些操作是合法的。 - 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
- 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)
题解:
- 创建两个列表,列表1用来存储数据,将原来的数据按顺序进入列表1,列表2当临时列表
- 执行push操作时先将x放入列表2,之后将列表1中的元素按0到-1的顺序pop进入列表2。列表1与列表2相等,再之后释放列表2空间
- top操作每次返回列表中第一个元素
- pop操作也是返回列表中第一个弹出的值
- empty操作如代码所示
最重要的是push操作,当然,如果用pop操作做相应的也是可以的
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.q=[]
self.p=[]
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.p.append(x)
while len(self.q)!=0:
self.p.append(self.q.pop(0))
self.q=self.p
self.p=[]
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.q.pop(0)
def top(self) -> int:
"""
Get the top element.
"""
return self.q[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return not bool(self.q)
232.用栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
- void push(int x) 将元素 x 推到队列的末尾
- int pop() 从队列的开头移除并返回元素
- int peek() 返回队列开头的元素
- boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
- 你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty操作是合法的。
- 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
题解:
- 创建两个栈,栈1用来存储数据,栈2当临时栈
- push操作时,将栈1中的元素调入临时栈利用临时栈调换顺序,之后将新数据push进入临时栈,最后将临时栈的数据pop进栈1
- pop、top、empty操作与上题类似
代码
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.q=[]
self.p=[]
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
while self.q:
self.p.append(self.q.pop(0))
self.p.append(x)
while self.p:
self.q.append(self.p.pop(0))
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
return self.q.pop(0)
def peek(self) -> int:
"""
Get the front element.
"""
return self.q[0]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return not bool(self.q)
155.最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) —— 将元素 x 推入栈中。
- pop() —— 删除栈顶的元素。
- top() —— 获取栈顶元素。
- getMin() —— 检索栈中的最小元素。
提示:
pop、top 和 getMin 操作总是在 非空栈 上调用。
题解:
- 设置一个minvalue,建立两个栈,栈1用来push数据,栈2存储到当前位置最小的数据
- 每push一个数据,将数据与minvalue比较一下,见其中的最小值push进栈2
- getmin直接取minvalue
代码
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.q=[]
self.p=[math.inf]
def push(self, x: int) -> None:
self.q.append(x)
self.p.append(min(x,self.p[-1]))
def pop(self) -> None:
self.q.pop()
self.p.pop()
def top(self) -> int:
return self.q[-1]
def getMin(self) -> int:
return self.p[-1]
946.验证栈序列
给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。
提示:
- 0 <= pushed.length == popped.length <= 1000
- 0 <= pushed[i], popped[i] < 1000
- pushed 是 popped 的排列。
题解:
- 创建一个栈stack存储pushed的数据
- 单个循环存储pushed的数据,每次循环遇到stack[-1]==poped[0]时,stack和poped都pop一个元素
- 最后如果stack为空,则为正确,其他则为错误
代码:
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
self.stack=[]
for i in range(len(pushed)):
self.stack.append(pushed[i])
while len(self.stack)>0 and self.stack[-1]==popped[0]:
self.stack.pop(-1)
popped.pop(0)
if self.stack:
return False
return True
215.数组中的第K个最大元素
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
题解:
建立一个n个数值的大根堆,删除n-k的数值,最后堆顶的值即为第k大元素
代码:
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
def heap_sort(nums,root,last_index):
left=2*root+1
while left<=last_index:
if left == last_index:
if nums[left]>nums[root]:
nums[left],nums[root] = nums[root],nums[left]
break
if nums[left+1]>nums[left]:
left += 1
if nums[root]<nums[left]:
nums[root],nums[left]=nums[left],nums[root]
root=left
left=2*root+1
else:
break
for i in range(int((len(nums)-1)/2),-1,-1):
heap_sort(nums,i,len(nums)-1)
#交换第一个和最后一个数
for last_index in range(len(nums) - 1, -1, -1):
nums[0], nums[last_index] = nums[last_index], nums[0]
k -= 1
if k == 0:
return nums[last_index]
heap_sort(nums, 0, last_index - 1)