diff --git "a/problems/0151.347円277円273円350円275円254円345円255円227円347円254円246円344円270円262円351円207円214円347円232円204円345円215円225円350円257円215円.md" "b/problems/0151.347円277円273円350円275円254円345円255円227円347円254円246円344円270円262円351円207円214円347円232円204円345円215円225円350円257円215円.md" index 0c1a526f38..111c07e4f5 100644 --- "a/problems/0151.347円277円273円350円275円254円345円255円227円347円254円246円344円270円262円351円207円214円347円232円204円345円215円225円350円257円215円.md" +++ "b/problems/0151.347円277円273円350円275円254円345円255円227円347円254円246円344円270円262円351円207円214円347円232円204円345円215円225円350円257円215円.md" @@ -311,7 +311,7 @@ class Solution { ``` ```java -//解法三:双反转+移位,在原始数组上进行反转。空间复杂度O(1) +//解法三:双反转+移位,String 的 toCharArray() 方法底层会 new 一个和原字符串相同大小的 char 数组,空间复杂度:O(n) class Solution { /** * 思路: diff --git "a/problems/0225.347円224円250円351円230円237円345円210円227円345円256円236円347円216円260円346円240円210円.md" "b/problems/0225.347円224円250円351円230円237円345円210円227円345円256円236円347円216円260円346円240円210円.md" index 3de300c781..d89bf44bf4 100644 --- "a/problems/0225.347円224円250円351円230円237円345円210円227円345円256円236円347円216円260円346円240円210円.md" +++ "b/problems/0225.347円224円250円351円230円237円345円210円227円345円256円236円347円216円260円346円240円210円.md" @@ -454,13 +454,34 @@ class MyStack: def top(self) -> int: """ + 写法一: 1. 首先确认不空 - 2. 我们仅有in会存放数据,所以返回第一个即可 + 2. 我们仅有in会存放数据,所以返回第一个即可(这里实际上用到了栈) + 写法二: + 1. 首先确认不空 + 2. 因为队列的特殊性,FIFO,所以我们只有在pop()的时候才会使用queue_out + 3. 先把queue_in中的所有元素(除了最后一个),依次出列放进queue_out + 4. 交换in和out,此时out里只有一个元素 + 5. 把out中的pop出来,即是原队列的最后一个,并使用temp变量暂存 + 6. 把temp追加到queue_in的末尾 """ + # 写法一: + # if self.empty(): + # return None + + # return self.queue_in[-1] # 这里实际上用到了栈,因为直接获取了queue_in的末尾元素 + + # 写法二: if self.empty(): return None + + for i in range(len(self.queue_in) - 1): + self.queue_out.append(self.queue_in.popleft()) - return self.queue_in[-1] + self.queue_in, self.queue_out = self.queue_out, self.queue_in + temp = self.queue_out.popleft() + self.queue_in.append(temp) + return temp def empty(self) -> bool: @@ -488,9 +509,19 @@ class MyStack: return self.que.popleft() def top(self) -> int: + # 写法一: + # if self.empty(): + # return None + # return self.que[-1] + + # 写法二: if self.empty(): return None - return self.que[-1] + for i in range(len(self.que)-1): + self.que.append(self.que.popleft()) + temp = self.que.popleft() + self.que.append(temp) + return temp def empty(self) -> bool: return not self.que