【LeetCode】155. 小栈

本文介绍了一种特殊的数据结构——最小值栈,它支持在常数时间内完成push、pop、top和getMin操作。通过使用链表实现,并维护一个额外的最小值链表,确保了在任何时候都能快速获取栈中的最小元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

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(x)——将元素x推入堆栈。
pop()——删除堆栈顶部的元素。
top()——获取top元素。
getMin()——检索堆栈中的最小元素。

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.

python实现

基本思路是用一个链表来实现栈,每次添加删除节点只对链表头进行处理。同时,为了能在常数时间返回栈的最小值,在栈里维护一个最小值链表,每当出现小于或等于当前最小值的新节点时,将其加入到该链表头,以保证每次能在常数时间返回最小值。

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None
        
class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.val = None
        self.next = None
        self.min = ListNode(None)
        

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        # Add new node and update the pointer of next.
        tmp = ListNode(None)
        tmp.val = self.val
        tmp.next = self.next
        
        self.val = x
        self.next = tmp
        
        # Update the list of min.
        if self.min == None or self.min.val == None:
            self.min = ListNode(x)
        elif x <= self.min.val: # Add the new minimum to the head.
            tmpMin = ListNode(None)
            tmpMin.val = self.min.val
            tmpMin.next = self.min.next
            
            self.min.val = x
            self.min.next = tmpMin
        

    def pop(self):
        """
        :rtype: None
        """
        
        if self.val == self.min.val:
            self.min = self.min.next
        
        self.val = self.next.val
        self.next = self.next.next
        

    def top(self):
        """
        :rtype: int
        """
        return self.val
        

    def getMin(self):
        """
        :rtype: int
        """
        return self.min.val
   
    


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

链接:https://leetcode.com/problems/min-stack/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值