leetcode | Min Stack

来源:互联网 发布:java房屋租赁管理系统 编辑:程序博客网 时间:2024/06/03 10:33

Min Stack: https://leetcode.com/problems/min-stack/
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

解析:
本题要求实现一个可以在常数时间返回最小值的栈。
由于会有出栈pop操作,所以用指针 min 记录最小值的位置,是不可取的。(最小值可能pop掉)

本文采用两个栈完成,一个栈elems存储元素,另一个栈mins存储最小值的元素。
mins stack 的push(x)操作时,只有在 x 小于等于 原最小值时,才入栈; pop()操作时,只有在elems的栈顶元素和最小值相等时,才出栈
本题难点在于想到用另一个栈维护最小值

class MinStack {private:    stack<int> elems;    stack<int> mins;public:    void push(int x) {        elems.push(x);        if (mins.empty() || x <= mins.top())            mins.push(x);    }    void pop() {        if (elems.top() == mins.top())            mins.pop();        elems.pop();    }    int top() {        return elems.top();    }    int getMin() {        return mins.top();    }};

如下算法采用原始操作(不使用STL容器库stack),leetcode 返回结果和自己用vs调试结果不同,因此未通过,不知原因,仅供参考。

#include <iostream>using namespace std;struct Node {    int val;    Node* next;};class MinStack {private:    Node* head;    Node* min;public:    MinStack() {        head = new Node;        head->next = NULL;        min = new Node;        min->next = NULL;    }    ~MinStack() {        delete head;        head = NULL;        delete min;        min = NULL;    }public:    void push(int x) {        Node* elem = new Node;        elem->val = x;        elem->next = head->next;        head->next = elem;        if (min->next == NULL || x <= min->val) {            Node* min_elem = new Node;            min_elem->val = x;            min_elem->next = min->next;            min->next = min_elem;        }    }    void pop() {        if (head->next == NULL)            return;        Node* top_elem = head->next;        head->next = head->next->next;        if (min->next != NULL && top_elem->val == min->next->val) {            Node* min_elem = min->next;            min->next = min->next->next;            delete min_elem;            min_elem = NULL;        }        delete top_elem;        top_elem = NULL;    }    int top() {        if (head->next == NULL)            return int();        return head->next->val;    }    int getMin() {        if (min->next == NULL)            return int();        return min->next->val;    }};int main() {    MinStack sol;    sol.push(-2);    sol.push(0);    sol.push(-1);    cout << sol.getMin() << endl;    cout << sol.top() << endl;;    sol.pop();    cout << sol.getMin() << endl;    sol.pop();    return 0;}
0 0
原创粉丝点击