LeetCode刷题笔记 155.最小栈

题目描述

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

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

总结

略看SDC1的时候感觉getMin()有问题,但其实push()和pop()写的很巧妙
比如依次录入5,4,3,2这组数据后,栈的数据为
MAX,5,__5,4,__4,3,_3,2
往前数组中第二小的数,往前数组中最小的数

SDC2用的一个辅助栈,与数据栈同步记录

Sample & Demo Code 1

class MinStack {
   int min = Integer.MAX_VALUE;
   private  Stack<Integer> stack ;
    public MinStack() {
      stack = new Stack<Integer>();
    }
    
    public void push(int x) {
        if(x <= min){          
            stack.push(min);
            min=x;
        }
        stack.push(x);     
    }
    
    public void pop() {
        if(stack.pop() == min) min=stack.pop();
    }
    
    public int top() {
       return stack.peek();
    }
    
    public int getMin() {
          return min;
    }
}

Sample & Demo Code 2

class MinStack {
    /** initialize your data structure here. */
    private int[] s;
    private int[] min;
    private int top;
    public MinStack() {
        s = new int[10];
        min = new int[10];
        top = -1;
    }
    
    public void push(int x) {
        if (top == s.length-1) {
            int[] temps = new int [s.length*2];
            int[] tempm = new int [s.length*2];
            for (int i = 0; i < s.length; i++){
                temps[i] = s[i];
                tempm[i] = min[i];
            }
            s = temps;
            min = tempm;
        }
        
        s[top+1] = x;
        if (top < 0)
            min[top+1] = x;
        else
            min[top+1] = x < min[top] ? x : min[top];
        
        top++;
    }

    public void pop() {
        if (top >= 0) top--;
    }

    public int top() {
        if (top >= 0) 
            return s[top];
        else 
            return -1;
        
    }

    public int getMin() {
        return min[top];
    }
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值