力扣hot100 最小栈 变种栈

Problem: 155. 最小栈
力扣hot100 最小栈 变种栈_第1张图片

文章目录

  • 思路
  • Stack + 自定义 Node
  • Code

思路

‍ 甜姨
力扣hot100 最小栈 变种栈_第2张图片

Stack + 自定义 Node

时间复杂度: O ( 1 ) O(1) O(1)

空间复杂度: O ( n ) O(n) O(n)

Code

class MinStack {

 	private Stack stack;

	class Node
	{
		int x;
		int min;

		public Node(int x, int min)
		{
			super();
			this.x = x;
			this.min = min;
		}
	}

	public MinStack()
	{
		stack = new Stack<>();
	}

	public void push(int x)
	{
		if (stack.isEmpty())
			stack.add(new Node(x, x));
		else
			stack.add(new Node(x, Math.min(x, stack.peek().min)));
	}

	public void pop()
	{
		stack.pop();
	}

	public int top()
	{
		return stack.peek().x;
	}

	public int getMin()
	{
		return stack.peek().min;
	}
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

你可能感兴趣的:(力扣,hot100,leetcode,算法,职场和发展)