鏈接
https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
耗時
解題:10 min
題解:9 min
題意
用兩個棧實現一個隊列。
隊列的聲明如下,請實現它的兩個函數 appendTail 和 deleteHead ,分別完成在隊列尾部插入整數和在隊列頭部刪除整數的功能。(若隊列中沒有元素,deleteHead 操作返回 -1 )
思路
設置兩個棧,st1 和 st2。
入隊時,直接把元素放入 st1。
出隊時,先看 st2 是否爲空,如果爲空,將 st1 中的元素順序放入 st2 中,這樣 st2 中就可以是正常順序出棧了;如果 st2 不爲空,直接彈出 st2 棧頂元素返回即可。
PS: 出隊時別忘記檢查當 st2 爲空時,st1 是否爲空,如果 st1 也爲空,說明隊列中沒有元素,需要返回 -1。
AC代碼
class CQueue {
public:
stack<int> st1, st2;
CQueue() {
while(!st1.empty()) {
st1.pop();
}
while(!st2.empty()) {
st2.pop();
}
}
void appendTail(int value) {
st1.push(value);
}
int deleteHead() {
if(st2.empty()) {
if(st1.empty()) return -1;
while(!st1.empty()) {
st2.push(st1.top());
st1.pop();
}
}
int ans = st2.top();
st2.pop();
return ans;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/