我在LeetCode练习时遇到了一些奇怪的错误

I met some strange errors when I practiced in LeetCode

本文关键字:错误 LeetCode 练习 遇到 我在      更新时间:2023-10-16

我尝试使用堆栈来实现队列,描述。 我的解决方案如下:

class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> my_stack;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stack<int> my_new_stack;
my_new_stack.push(x);
for(int i = 0; i < my_stack.size();i++){
my_new_stack.push(my_stack.top());
my_stack.pop();
}
for(int i = 0; i< my_new_stack.size();i++){
my_stack.push(my_new_stack.top());
my_new_stack.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {  // what about queue is empty
int temp = my_stack.top(); 
my_stack.pop();
return temp;
}
/** Get the front element. */
int peek() {
return my_stack.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return my_stack.empty();
;
}

};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/

我的测试用例是


["MyQueue","empty","push","push","push","pop","pop","pop"][[],[],[1],[2],[3],[],[],[]]

而结果是[null,true,null,null,null,1,0,80]真正的结果是[null,true,null,null,null,1,2,3]

我知道效率很尴尬,但我真的不知道080从哪里来的。

感谢您的帮助!

仔细看看这个:

for(int i = 0; i < my_stack.size();i++){
my_new_stack.push(my_stack.top());
my_stack.pop();
}

并心想:每次通过循环,我的i < my_stack.size()状况的结果是什么。提示:它并不总是堆栈的原始大小。

只要my_stack

不是空的,你最好从my_stack转移到my_new_stack

而且,是的,强调这个词是有原因的,轻推轻推眨眼:-(


我还想指出,你可以让这个方案更有效率一点。您将堆栈保持在始终准备好提取的状态。但是想想如果你在提取任何项目之前插入一千个项目会发生什么。

这是堆栈上所有项目的两千次反转。

更好的方法是存储当前模式(插入或提取(,并且仅在需要时反转。

例如,请参阅以下伪代码:

def init():
# Initialise in insert mode.
stack = []
mode = mode_insert
def reverseStack():
# Transfer all items to get reverse order.
newStack = []
while not stack.empty():
newStack.push(stack.top())
stack.pop()
# Use reversed stack now.
stack = newStack
# Change mode.
if mode == mode_insert:
mode = mode_extract
else mode = mode_insert
def insert(item):
# Put stack in right state and add the item.
if mode == mode_extract:
reverseStack()
stack.push(item)
def extract():
# Put stack in right state then get item out.
if mode == mode_insert:
reverseStack()
item = stack.top()
stack.pop()
return item

如果您长时间运行类似的操作,这实际上会更有效率,如果您在插入和提取之间交替,效率会略低。

首先,你的推送方法存在逻辑错误,你应该确保新的int值应该被推到my_stack的底部(交换后(。

其次,在函数中,stack.size((不是不变的,它总是变化的,你同时使用i++,所以你丢失了一些元素。我更喜欢同时。

我不擅长英语,希望你能理解我。