目錄
- 1.問題描述
- 2.測試用例
- 示例 1
- 3.提示
- 4.代碼
- 1.入隊反轉
- code
- 複雜度
- 2.出隊反轉
- 1.入隊反轉
請你僅使用兩個棧實作先入先出隊列。隊列應當支援一般隊列支援的所有操作(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(雙端隊列)來模拟一個棧,隻要是标準的棧操作即可。
輸入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 1, 1, false]
解釋:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
- 1 <= x <= 9
- 最多調用 100 次 push、pop、peek 和 empty
- 假設所有操作都是有效的 (例如,一個空的隊列不會調用 pop 或者 peek 操作)
- 進階:你能否實作每個操作均攤時間複雜度為
的隊列?換句話說,執行O(1)
個操作的總時間複雜度為n
,即使其中一個操作可能花費較長時間。O(n)
public class MyQueueWithInputReverse {
private Stack<Integer> st1;
private Stack<Integer> st2;
public MyQueueWithInputReverse() {
st1 = new Stack<>();
st2 = new Stack<>();
}
public void push(int x) {
while (!st1.isEmpty()) {
st2.push(st1.pop());
}
st1.push(x);
while (!st2.isEmpty()) {
st1.push(st2.pop());
}
}
public int pop() {
return st1.pop();
}
public int peek() {
return st1.peek();
}
public boolean empty() {
return st1.isEmpty();
}
}
1.push()
* 時間複雜度:O(n)
* 空間複雜度:O(n)
2.pop()
* 時間複雜度:O(1)
* 空間複雜度:O(1)
3.peek()
* 時間複雜度:O(1)
* 空間複雜度:O(1)
4.empty()
* 時間複雜度:O(1)
* 空間複雜度:O(1)
public class MyQueueWithOutputReverse {
private Stack<Integer> st1;
private Stack<Integer> st2;
public MyQueueWithOutputReverse() {
st1 = new Stack<>();
st2 = new Stack<>();
}
public void push(int x) {
st1.push(x);
}
public int pop() {
if (!st2.isEmpty()) {
return st2.pop();
} else {
while (!st1.isEmpty()) {
st2.push(st1.pop());
}
return st2.pop();
}
}
public int peek() {
if (!st2.isEmpty()) {
return st2.peek();
} else {
while (!st1.isEmpty()) {
st2.push(st1.pop());
}
return st2.peek();
}
}
public boolean empty() {
return st1.isEmpty() && st2.isEmpty();
}
}
1.push()
* 時間複雜度:O(1)
* 空間複雜度:O(n)
2.pop()
* 時間複雜度:O(n)
* 空間複雜度:O(1)
3.peek()
* 時間複雜度:O(1)
* 空間複雜度:O(1)
4.empty()
* 時間複雜度:O(1)
* 空間複雜度:O(1)