8. Min Stack

Description:

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.

 

  按题意理解,可知这题主要是要实现栈的基本操作,唯一的难点在getMin()函数的实现。该函数的实现可以直接用两个vector容器实现(或者使用两个stack来实现)

  在程序中,我定义了两个vector,一个用于实现栈的基本操作,一个则用于存储当前最小元素

class MinStack {
  vector<int> a;
  vector<int> min;
public:
/** initialize your data structure here. */
MinStack() {
  min.push_back(2147483647);
}

void push(int x) {
  a.push_back(x);
  if(x<min.back()){
    min.push_back(x);
}
  else{
    min.push_back(min.back());
}

}

void pop() {
  a.pop_back();
  min.pop_back();

}

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

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

posted @ 2017-05-04 12:04  legooooo  阅读(103)  评论(0编辑  收藏  举报