LeetCode155——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.

题目大意

设计一个栈,支持push, pop, top,和在常量时间内返回最小元素。

难度系数:容易

分析

这题写出实现并不难,反而是让LeetCode能运行你的代码,比起解这题还费劲。比如,一开始,我使用了vector,结果出现运行时错误。 后来一查,是LeetCode的问题。就那我现在的实现代码来说,把_capacity的初始值改成10,程序运行正常,把它改成100,程序运行出错。 做完后,发现自己的实现和leetcode给出的思路是一致的,也让我颇感欣慰,尽管花了点时间。

实现

template <class T>
class Vector {
public:
    Vector():_capacity(10),_size(0),_pt(NULL) {
        _pt = (T*)malloc(_capacity*sizeof(T));
    }
    ~Vector(){
        free(_pt);
    }

    void push_back(T t) {
        if (_size >= _capacity) {
            _capacity = _capacity * 5;
            T* ptmp = (T*)realloc(_pt,  _capacity*sizeof(T));
            if (ptmp) {
                _pt = ptmp;
            }
        }

        _pt[_size] = t;
        _size++;
    }

    void pop_back() {
        if (_size > 0) {
            --_size;
        }
    }

    T& operator[](size_t pos) {
        return _pt[pos];
    }

    const T& operator[](size_t p) const {
        return _pt[p];
    }

    int erase(int i) {
        for (int k = i; k < _size-1; ++k) {
            _pt[k] = _pt[k+1];
        }
        _size = _size - 1;
        return i;
    }

    void insert(int pos, T t) {
        if (_size >= _capacity) {
            _capacity = _capacity * 5;
            T* ptmp = (T*)realloc(_pt,  _capacity*sizeof(T));
            if (ptmp) {
                _pt = ptmp;
            }
        }
        for (int i = _size; i > pos; --i) {
            _pt[i] = _pt[i-1];
        }
        _pt[pos] = t;
        _size += 1;
    }

    int size() const {
        return _size;
    }

    T back() const{
        return _pt[_size-1];
    }

    T front() const {
        return _pt[0];
    }

private:
    T* _pt;
    int _size;
    int _capacity;
};

class MinStack {
public:
    void push(int x) {
        v.push_back(x);
        if (ov.size() == 0) {
            ov.push_back(x);
        }
        else if (x <= ov.back())
            ov.push_back(x);
    }

    void pop() {
        if (v.size() <= 0)
            return;
        int val = v.back();
        v.pop_back();
        if (val == ov.back()) {
            ov.pop_back();
        }
    }

    int top() {
        return v.back();
    }

    int getMin() {
        return ov.back();
    }

    const Vector<int>& getV() const {
        return v;
    }
private:
    Vector<int> v;
    Vector<int> ov;
};

你可能感兴趣的:(LeetCode,栈,ACM,stack,min,LeetCode155)