设计包含min函数的栈

本文介绍了一种特殊的栈数据结构——MinStack,它支持push、pop和min三个操作,并且每个操作的时间复杂度均为O(1)。通过使用辅助栈来跟踪最小元素的位置,确保即使在元素出栈后也能快速找到新的最小值。

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

import java.util.ArrayList;   
import java.util.List;   
  
  
public class MinStack {   
  
    //maybe we can use origin array rather than ArrayList   
    private List<Integer> dataStack;   
    private List<Integer> auxStack;//store the position of MinElement   
       
    public static void main(String[] args) {   
        MinStack minStack=new MinStack();   
        minStack.push(3);   
        minStack.printStatus();   
        minStack.push(4);   
        minStack.printStatus();   
        minStack.push(2);   
        minStack.printStatus();   
        minStack.push(1);   
        minStack.printStatus();   
        minStack.pop();   
        minStack.printStatus();   
        minStack.pop();   
        minStack.printStatus();   
        minStack.push(0);   
        minStack.printStatus();   
    }   
  
    public MinStack(){   
        dataStack=new ArrayList<Integer>();   
        auxStack=new ArrayList<Integer>();   
    }   
    public void push(int item){   
        if(isEmpty()){   
            dataStack.add(item);   
            auxStack.add(0);//position=0   
        }else{   
            dataStack.add(item);   
            int minIndex=auxStack.get(auxStack.size()-1);   
            int min=dataStack.get(minIndex);   
            if(min>item){   
                auxStack.add(dataStack.size()-1);   
            }else{   
                auxStack.add(minIndex);   
            }   
        }   
    }   
    public int pop(){   
        int top=-1;   
        if(isEmpty()){   
            System.out.println("no element,no pop");   
        }else{   
            auxStack.remove(auxStack.size()-1);   
            top=dataStack.remove(dataStack.size()-1);   
        }   
        return top;   
           
    }   
    public int min(){   
        int min=-1;   
        if(!isEmpty()){   
            int minIndex=auxStack.get(auxStack.size()-1);   
            min=dataStack.get(minIndex);   
        }   
        return min;   
    }   
    public boolean isEmpty(){   
        return dataStack.size()==0;   
    }   
    public void printStatus(){   
        System.out.println("数据栈             辅助栈                最小值");   
        for(int i=0;i<dataStack.size();i++){   
            System.out.print(dataStack.get(i)+",");   
        }   
        System.out.print("          ");   
        for(int i=0;i<dataStack.size();i++){   
            System.out.print(auxStack.get(i)+",");   
        }   
        System.out.print("           ");   
        System.out.print(this.min());   
        System.out.println();   
    }   
    /*  
步骤              数据栈            辅助栈                最小值  
1.push 3    3          0             3  
2.push 4    3,4        0,0           3  
3.push 2    3,4,2      0,0,2         2  
4.push 1    3,4,2,1    0,0,2,3       1  
5.pop       3,4,2      0,0,2         2  
6.pop       3,4        0,0           3  
7.push 0    3,4,0      0,0,2         0  
     */  
}  

题目: 定义栈的数据结构,要求添加一个 min 函数,能够得到栈的最小元素。要求函数min push 以及pop 的时间复杂度都是O(1)

分析:这是去年google的一道面试题。

我看到这道题目时,第一反应就是每次push一个新元素时,将栈里所有逆序元素排序。这样栈顶元素将是最小元素。但由于不能保证最后push进栈的元素最先出栈,这种思路设计的数据结构已经不是一个栈了。

在栈里添加一个成员变量存放最小元素(或最小元素的位置)。每次push一个新元素进栈的时候,如果该元素比当前的最小元素还要小,则更新最小元素。

乍一看这样思路挺好的。但仔细一想,该思路存在一个重要的问题:如果当前最小元素被pop出去,如何才能得到下一个最小元素?

因此仅仅只添加一个成员变量存放最小元素(或最小元素的位置)是不够的。我们需要一个辅助栈,每次push一个新元素的时候,同时将最小元素(或最小元素的位置,考虑到栈元素的类型可能是复杂的数据结构,用最小元素的位置将能减少空间消耗)push到辅助栈中;每次pop一个元素出栈的时候,同时pop辅助栈

参考代码:

复制代码
#include <deque>
#include <assert.h>

template <typename T> 
class CStackWithMin
{
public:
      CStackWithMin(void) {}
      virtual ~CStackWithMin(void) {}

      T& top(void);
      const T& top(void) const;

      void push(const T& value);
      void pop(void);

      const T& min(void) const;

private:
     stack<T> m_data;               // the elements of stack
     statck<size_t> m_minIndex;      // the indices of minimum elements
};

// get the last element of mutable stack
template <typename T> 
T& CStackWithMin<T>::top() {
      return m_data.back();
}

// get the last element of non-mutable stack
template <typename T> 
const T& CStackWithMin<T>::top() const {
      return m_data.back();
}

// insert an elment at the end of stack
template <typename T> 
void CStackWithMin<T>::push(const T& value) {
      // append the data into the end of m_data
      m_data.push_back(value);

      // set the index of minimum elment in m_data at the end of m_minIndex
      if(m_minIndex.size() == 0)
            m_minIndex.push_back(0);
      else {
            if(value < m_data[m_minIndex.back()])
                  m_minIndex.push_back(m_data.size() - 1);
            else
                  m_minIndex.push_back(m_minIndex.back());
      }
}

// erease the element at the end of stack
template <typename T> 
void CStackWithMin<T>::pop() {
      // pop m_data
      m_data.pop_back();

      // pop m_minIndex
      m_minIndex.pop_back();
}

// get the minimum element of stack
template <typename T> 
const T& CStackWithMin<T>::min() const {
      assert(m_data.size() > 0);
      assert(m_minIndex.size() > 0);

      return m_data[m_minIndex.back()];
}
复制代码

举个例子演示上述代码的运行过程:

步骤 数据栈 辅助栈 最小值
1.push 3 3 0 3
2.push 4 3,4 0,0 3
3.push 2 3,4,2 0,0,2 2
4.push 1 3,4,2,1 0,0,2,3 1
5.pop 3,4,2 0,0,2 2
6.pop 3,4 0,0 3
7.push 0 3,4,0 0,0,2 0



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值