Skip to content

Commit

Permalink
修复 47~541连接更新 代码丢失
Browse files Browse the repository at this point in the history
  • Loading branch information
youngyangyang04 committed Aug 25, 2021
1 parent 7fb96fd commit 45aa719
Show file tree
Hide file tree
Showing 10 changed files with 267 additions and 300 deletions.
48 changes: 25 additions & 23 deletions problems/0150.逆波兰表达式求值.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# 150. 逆波兰表达式求值

[力扣题目链接](https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/)
https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

根据 逆波兰表示法,求表达式的值。

Expand All @@ -23,7 +23,7 @@

整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

 

示例 1:
* 输入: ["2", "1", "+", "3", " * "]
Expand All @@ -40,13 +40,13 @@
* 输出: 22
* 解释:该算式转化为常见的中缀算术表达式为:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
 

逆波兰表达式:是一种后缀表达式,所谓后缀就是指算符写在后面。

Expand All @@ -62,20 +62,20 @@

# 思路

在上一篇文章中[1047.删除字符串中的所有相邻重复项](https://programmercarl.com/1047.删除字符串中的所有相邻重复项.html)提到了 递归就是用栈来实现的。
在上一篇文章中[1047.删除字符串中的所有相邻重复项](https://mp.weixin.qq.com/s/1-x6r1wGA9mqIHW5LrMvBg)提到了 递归就是用栈来实现的。

所以**栈与递归之间在某种程度上是可以转换的!** 这一点我们在后续讲解二叉树的时候,会更详细的讲解到。

那么来看一下本题,**其实逆波兰表达式相当于是二叉树中的后序遍历**。 大家可以把运算符作为中间节点,按照后序遍历的规则画出一个二叉树。

但我们没有必要从二叉树的角度去解决这个问题,只要知道逆波兰表达式是用后续遍历的方式把二叉树序列化了,就可以了。

在进一步看,本题中每一个子表达式要得出一个结果,然后拿这个结果再进行运算,那么**这岂不就是一个相邻字符串消除的过程,和[1047.删除字符串中的所有相邻重复项](https://programmercarl.com/1047.删除字符串中的所有相邻重复项.html)中的对对碰游戏是不是就非常像了。**
在进一步看,本题中每一个子表达式要得出一个结果,然后拿这个结果再进行运算,那么**这岂不就是一个相邻字符串消除的过程,和[1047.删除字符串中的所有相邻重复项](https://mp.weixin.qq.com/s/1-x6r1wGA9mqIHW5LrMvBg)中的对对碰游戏是不是就非常像了。**

如动画所示:
![150.逆波兰表达式求值](https://code-thinking.cdn.bcebos.com/gifs/150.逆波兰表达式求值.gif)

相信看完动画大家应该知道,这和[1047. 删除字符串中的所有相邻重复项](https://programmercarl.com/1047.删除字符串中的所有相邻重复项.html)是差不错的,只不过本题不要相邻元素做消除了,而是做运算!
相信看完动画大家应该知道,这和[1047. 删除字符串中的所有相邻重复项](https://mp.weixin.qq.com/s/1-x6r1wGA9mqIHW5LrMvBg)是差不错的,只不过本题不要相邻元素做消除了,而是做运算!

C++代码如下:

Expand Down Expand Up @@ -223,17 +223,19 @@ var evalRPN = function(tokens) {
python3

```python
def evalRPN(tokens) -> int:
stack = list()
for i in range(len(tokens)):
if tokens[i] not in ["+", "-", "*", "/"]:
stack.append(tokens[i])
else:
tmp1 = stack.pop()
tmp2 = stack.pop()
res = eval(tmp2+tokens[i]+tmp1)
stack.append(str(int(res)))
return stack[-1]
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for item in tokens:
if item not in {"+", "-", "*", "/"}:
stack.append(item)
else:
first_num, second_num = stack.pop(), stack.pop()
stack.append(
int(eval(f'{second_num} {item} {first_num}')) # 第一个出来的在运算符后面
)
return int(stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的

```


Expand Down
69 changes: 41 additions & 28 deletions problems/0225.用队列实现栈.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# 225. 用队列实现栈

[力扣题目链接](https://leetcode-cn.com/problems/implement-stack-using-queues/)
https://leetcode-cn.com/problems/implement-stack-using-queues/

使用队列实现栈的下列操作:

Expand All @@ -34,7 +34,7 @@

有的同学可能疑惑这种题目有什么实际工程意义,**其实很多算法题目主要是对知识点的考察和教学意义远大于其工程实践的意义,所以面试题也是这样!**

刚刚做过[栈与队列:我用栈来实现队列怎么样?](https://programmercarl.com/0232.用栈实现队列.html)的同学可能依然想着用一个输入队列,一个输出队列,就可以模拟栈的功能,仔细想一下还真不行!
刚刚做过[栈与队列:我用栈来实现队列怎么样?](https://mp.weixin.qq.com/s/Cj6R0qu8rFA7Et9V_ZMjCA)的同学可能依然想着用一个输入队列,一个输出队列,就可以模拟栈的功能,仔细想一下还真不行!

**队列模拟栈,其实一个队列就够了**,那么我们先说一说两个队列来实现栈的思路。

Expand Down Expand Up @@ -294,53 +294,66 @@ Python:

```python
from collections import deque

class MyStack:

def __init__(self):
"""
Initialize your data structure here.
Python普通的Queue或SimpleQueue没有类似于peek的功能
也无法用索引访问,在实现top的时候较为困难。
用list可以,但是在使用pop(0)的时候时间复杂度为O(n)
因此这里使用双向队列,我们保证只执行popleft()和append(),因为deque可以用索引访问,可以实现和peek相似的功能
in - 存所有数据
out - 仅在pop的时候会用到
"""
#使用两个队列来实现
self.que1 = deque()
self.que2 = deque()
self.queue_in = deque()
self.queue_out = deque()

def push(self, x: int) -> None:
"""
Push element x onto stack.
直接append即可
"""
self.que1.append(x)
self.queue_in.append(x)


def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
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()的时候两个进行交换
"""
size = len(self.que1)
size -= 1#这里先减一是为了保证最后面的元素
while size > 0:
size -= 1
self.que2.append(self.que1.popleft())

if self.empty():
return None

result = self.que1.popleft()
self.que1, self.que2= self.que2, self.que1#将que2和que1交换 que1经过之前的操作应该是空了
#一定注意不能直接使用que1 = que2 这样que2的改变会影响que1 可以用浅拷贝
return result
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:
"""
Get the top element.
1. 首先确认不空
2. 我们仅有in会存放数据,所以返回第一个即可
"""
return self.que1[-1]
if self.empty():
return None

return self.queue_in[-1]


def empty(self) -> bool:
"""
Returns whether the stack is empty.
因为只有in存了数据,只要判断in是不是有数即可
"""
#print(self.que1)
if len(self.que1) == 0:
return True
else:
return False

return len(self.queue_in) == 0

```

Expand Down
106 changes: 35 additions & 71 deletions problems/0232.用栈实现队列.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# 232.用栈实现队列

[力扣题目链接](https://leetcode-cn.com/problems/implement-queue-using-stacks/)
https://leetcode-cn.com/problems/implement-queue-using-stacks/

使用栈实现队列的下列操作:

Expand Down Expand Up @@ -129,54 +129,6 @@ public:
Java:
使用Stack(堆栈)同名方法:
```java
class MyQueue {
// java中的 Stack 有设计上的缺陷,官方推荐使用 Deque(双端队列) 代替 Stack
Deque<Integer> stIn;
Deque<Integer> stOut;
/** Initialize your data structure here. */
public MyQueue() {
stIn = new ArrayDeque<>();
stOut = new ArrayDeque<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
// 只要 stOut 为空,那么就应该将 stIn 中所有的元素倒腾到 stOut 中
if (stOut.isEmpty()) {
while (!stIn.isEmpty()) {
stOut.push(stIn.pop());
}
}
// 再返回 stOut 中的元素
return stOut.pop();
}
/** Get the front element. */
public int peek() {
// 直接使用已有的pop函数
int res = this.pop();
// 因为pop函数弹出了元素res,所以再添加回去
stOut.push(res);
return res;
}
/** Returns whether the queue is empty. */
public boolean empty() {
// 当 stIn 栈为空时,说明没有元素可以倒腾到 stOut 栈了
// 并且 stOut 栈也为空时,说明没有以前从 stIn 中倒腾到的元素了
return stIn.isEmpty() && stOut.isEmpty();
}
}
```


```java
class MyQueue {
Expand Down Expand Up @@ -234,48 +186,60 @@ class MyQueue {

Python:
```python
# 使用两个栈实现先进先出的队列
class MyQueue:

def __init__(self):
"""
Initialize your data structure here.
in主要负责push,out主要负责pop
"""
self.stack1 = list()
self.stack2 = list()
self.stack_in = []
self.stack_out = []


def push(self, x: int) -> None:
"""
Push element x to the back of queue.
有新元素进来,就往in里面push
"""
# self.stack1用于接受元素
self.stack1.append(x)
self.stack_in.append(x)


def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
1. 检查如果out里面元素,则直接pop
2. 如果out没有元素,就把in里面的元素(除了第一个)依次pop后装进out里面
3. 直接把in剩下的元素pop出来,就是queue头部的
"""
# self.stack2用于弹出元素,如果self.stack2为[],则将self.stack1中元素全部弹出给self.stack2
if self.stack2 == []:
while self.stack1:
tmp = self.stack1.pop()
self.stack2.append(tmp)
return self.stack2.pop()
if self.empty:
return None

if self.stack_out:
return self.stack_out.pop()
else:
for i in range(1, len(self.stack_in)):
self.stack_out.append(self.stack_in.pop())
return self.stack_in.pop()


def peek(self) -> int:
"""
Get the front element.
1. 查out有没有元素,有就把最上面的返回
2. 如果out没有元素,就把in最下面的返回
"""
if self.stack2 == []:
while self.stack1:
tmp = self.stack1.pop()
self.stack2.append(tmp)
return self.stack2[-1]
if self.empty:
return None

if self.stack_out:
return self.stack_out[-1]
else:
return self.stack_in[0]


def empty(self) -> bool:
"""
Returns whether the queue is empty.
只要in或者out有元素,说明队列不为空
"""
return self.stack1 == [] and self.stack2 == []
return not (self.stack_in or self.stack_out)

```


Expand Down
Loading

0 comments on commit 45aa719

Please sign in to comment.