MinStack-leetcode155

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.blog

  • 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.

Example:隊列

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

 

這裏原本覺得用上stack類,能夠垂手可得的實現,固然我還能夠使用其餘的隊列實現。只是getMin要特殊處理一下,畢竟statck就只有那幾個方法,會比較麻煩一點,可是看到別的大神是那麼寫的,智商抓急,這樣寫的確比較方便,就是若是想看size會比較奇怪!element

本站公眾號
   歡迎關注本站公眾號,獲取更多信息