所以我在leetcode上做一道题。它是使用队列实现堆栈。 如果我在下面提交此代码。它被接受。
class Stack {
public:
queue<int> que;
// Push element x onto stack.
void push(int x) {
que.push(x);
for(int i=0;i<que.size()-1;i++){
que.push(que.front());
que.pop();
}
}
// Removes the element on top of the stack.
void pop() {
que.pop();
}
// Get the top element.
int top() {
return que.front();
}
// Return whether the stack is empty.
bool empty() {
return que.empty();
}
};
但如果我只改变 for(int i=0;i<que.size()-1;++i)
至 for(int i=0;i<=que.size()-2;i++)
,我超出了时间限制。最后执行的输入:push(1),empty()。有人能告诉我为什么吗???谢谢
最佳答案
queue::size()
返回一个 size_t,它基本上是一个无符号数。和一个负无符号数转换为一个巨大的数字。
所以 queue::size()-1
--> 巨大的数字 (0xFFFFFFFF)
关于c++ - 同样的表达方式却不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34317205/