寫在前面
最近刷阿里的題庫,看到了一道用棧實現最小堆的題目,然後就找到了一系列棧模擬其他數據結構的題目,這裏整理一下。這些題目對熟悉這些基本的數據結構幫助很大。
232. 用棧實現隊列
使用棧實現隊列的下列操作:
push(x) – 將一個元素放入隊列的尾部。
pop() – 從隊列首部移除元素。
peek() – 返回隊列首部的元素。
empty() – 返回隊列是否爲空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
說明:
- 你只能使用標準的棧操作 – 也就是隻有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
- 你所使用的語言也許不支持棧。你可以使用 list 或者 deque(雙端隊列)來模擬一個棧,只要是標準的棧操作即可。
- 假設所有操作都是有效的 (例如,一個空的隊列不會調用 pop 或者 peek 操作)。
解法:
其實就是用棧實現一個隊列的操作,這裏需要搞清楚的就是兩個數據其實是完全相反的,這也是這題的難點所在:
- 棧:LIFO 後進先出
- 隊列:FIFO 先進先出
受到 @liweiwei 大佬的啓發,其實可以發現兩個數據結構就是反了過來,那麼使用兩個棧,一個棧(stackPush)用於元素進棧,一個棧(stackPop)用於元素出棧;
pop() 或者 top() 的時候:
- 如果 stackPop 裏面有元素,直接從 stackPop 進行pop()和top()操作。
- 如果 stackPop 裏面沒有元素,一次性將 stackPush 裏面的所有元素倒入 stackPop。
代碼:
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> spop;
stack<int> spush;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
spush.push(x);
}
void shift(){//倒進去的過程,用函數單獨寫,簡化代碼
if(spop.empty()){//只有空的之後纔開始倒,因爲空的時候意味着棧底沒有元素了
while(!spush.empty()){
spop.push(spush.top());
spush.pop();
}
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
shift();
int tmp = spop.top();
spop.pop();
return tmp;
}
/** Get the front element. */
int peek() {
shift();
return spop.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return (spop.empty()&&spush.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();
*/
155. 最小棧
設計一個支持 push ,pop ,top 操作,並能在常數時間內檢索到最小元素的棧。
push(x) —— 將元素 x 推入棧中。
pop() —— 刪除棧頂的元素。
top() —— 獲取棧頂元素。
getMin() —— 檢索棧中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
解法:
因爲有個getMin函數,而且要求在O(1)時間完成,所以需要再維護一個棧,這個棧的棧頂是最小值。
最小值棧的維護,分兩種,同步數據和不同步數據,差別其實不大而且思路是一致的:
- 當最小值棧爲空時,直接插入新元素
- 當最小值棧棧頂大於等於新元素,插入新元素。
同步和不同步就是在空間上面有細微差異,同步的棧會有無用元素,不同步的話會多一些邊界計算,性能上面有細微差異。
代碼(同步):
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s;
stack<int> helper;
MinStack() {
}
void push(int x) {
s.push(x);
if(helper.empty() || helper.top()>=x)
helper.push(x);
else
helper.push(helper.top());//同步
}
void pop() {
if(!s.empty()){
s.pop();
helper.pop();
}
}
int top() {
if(!s.empty())return s.top();
return 0;
}
int getMin() {
if(!helper.empty())return helper.top();
return 0;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
代碼(不同步):
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s;
stack<int> helper;
MinStack() {
}
void push(int x) {
s.push(x);
if(helper.empty() || helper.top()>=x){
helper.push(x);
}
}
void pop() {
if(!s.empty()){
if(!helper.empty()&&s.top()==helper.top()){
helper.pop();
}
s.pop();
}
}
int top() {
if(!s.empty())return s.top();
return 0;
}
int getMin() {
if(!helper.empty())return helper.top();
return 0;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
716. 最大棧
設計一個最大棧,支持 push、pop、top、peekMax 和 popMax 操作。
- push(x) – 將元素 x 壓入棧中。
- pop() – 移除棧頂元素並返回這個值。
- top() – 返回棧頂元素。
- peekMax() – 返回棧中最大元素。
- popMax() – 返回棧中最大的元素,並將其刪除。如果有多個最大元素,只要刪除最靠近棧頂的那個。
樣例 1:
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5
註釋:
- -1e7 <= x <= 1e7
- 操作次數不會超過 10000。
- 當棧爲空的時候不會出現後四個操作。
解法:
雙棧
這題和最小棧那題很像,但是多了一個popmax的操作,就複雜了很多,意味着要找到max並刪除,這題就有這一個難點,需要一個臨時棧實現這個popmax。
代碼:
class MaxStack {
public:
/** initialize your data structure here. */
stack s;
stack maxs;
MaxStack() {
}
void push(int x) {
s.push(x);
if(maxs.empty()||x>=maxs.top())
maxs.push(x);
}
int pop() {
int tmp = s.top();
s.pop();
if(maxs.top()==tmp) maxs.pop();
return tmp;
}
int top() {
return s.top();
}
int peekMax() {
return maxs.top();
}
int popMax() {
stack<int> buffer;
int maxn = maxs.top();
maxs.pop();
while(s.top()!=maxn){
buffer.push(s.top());
s.pop();
}
s.pop();
while(!buffer.empty()){
push(buffer.top());//這裏如果用s.push就會重複調用,所以直接push
buffer.pop();
}
return maxn;
}
};
/**
- Your MaxStack object will be instantiated and called as such:
- MaxStack* obj = new MaxStack();
- obj->push(x);
- int param_2 = obj->pop();
- int param_3 = obj->top();
- int param_4 = obj->peekMax();
- int param_5 = obj->popMax();
*/
用了兩個棧,還要O(N)的時間,就很難受,所以我們要再想想有沒有更優的解法。
平衡樹+鏈表
平衡樹中的每一個節點存儲一個鍵值對,其中“鍵”表示某個在棧中出現的值,“值”爲一個列表。時間複雜度:O(log(n))
代碼:
class MaxStack {
public:
/** initialize your data structure here. */
list<int> l;
map<int, vector<list<int>::iterator>> mp;
MaxStack() {
}
void push(int x) {
l.push_front(x);
mp[x].push_back(l.begin());
}
int pop() {
int key = l.front();
mp[key].pop_back();
if(mp[key].empty()) mp.erase(key);
l.pop_front();
return key;
}
int top() {
return l.front();
}
int peekMax() {
//rbegin() 返回一個逆序迭代器,它指向容器的最後一個元素
return mp.rbegin()->first;
}
int popMax() {
int key = mp.rbegin()->first;
auto it = mp[key].back();
mp[key].pop_back();
if(mp[key].empty()) mp.erase(key);
l.erase(it);
return key;
}
};