leetcode刷题笔记一百五十五题 最小栈

leetcode刷题笔记一百五十五题 最小栈

源地址:155. 最小栈

问题描述:

设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。

示例:

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.

//使用两个栈构建
import scala.collection.mutable

class MinStack {

  /** initialize your data structure here. */
  private val mins = mutable.Stack[Int]()
  private val stack = mutable.Stack[Int]()

  def top (): Int = {
    stack.top
  }

  def getMin (): Int = {
    mins.top
  }

  def push (x: Int) = {
    if (mins.isEmpty || mins.top >= x)
      mins.push(x)
    stack.push(x)
  }

  def pop () = {
    if (mins.top == top)
      mins.pop()
    stack.pop()
  }
}

//使用链表
class MinStack() {

    /** initialize your data structure here. */
    case class Node (value: Int, min: Int, next: Node)
    var head: Node = null

    def push(x: Int) {
        if (head == null) head = Node(x, x, null)
        else  head = Node(x, Math.min(x, head.min), head)
    }

    def pop() {
        if (head != null) head = head.next 
    }

    def top(): Int = {
        head.value
    }

    def getMin(): Int = {
        head.min
    }

}

/**
 * Your MinStack object will be instantiated and called as such:
 * var obj = new MinStack()
 * obj.push(x)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */
原文地址:https://www.cnblogs.com/ganshuoos/p/13595387.html