当前位置: 移动技术网 > IT编程>网页制作>CSS > LeetCode解析------155.最小栈-设计

LeetCode解析------155.最小栈-设计

2020年07月17日  | 移动技术网IT编程  | 我要评论

题目:

设计一个支持 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.

提示:

pop、top 和 getMin 操作总是在 非空栈 上调用。

简单介绍:
题目:最小栈
题目难度:简单
使用语言:JAVA。
这道题来自leetcode题库的设计标签。

解题思路:
首先看题、分析题意,我们可以明确1个关键点:
1.维护一个堆栈
2.维护一个最小值

既然,我们已经分析出来题目的关键任务了,下面我们就可以开始思考实现了。
我们采用算法与数据结构的思路来剖析一下这题,

数据结构:
要实现对数据的操作,我们要先明确存储数据的数据结构。
该题的数据结构的作用:
1.采用链表的方式来保存整个栈

算法:
既然明确了我们的数据结构,我们就可以开始我们的算法分析了。
1.第一步,初始化工作。
2.第二步,设置入栈,出栈,取栈,取最小值函数

代码部分:


public class MinStack {
    //内部
    class Node{
        int value;
        int min;
        Node next;

        Node(int v,int m){
            value=v;
            min=m;
            next=null;
        }
    }
    Node head;

    /** initialize your data structure here. */
    public MinStack() {
        head=null;
    }

    public void push(int x) {
        if(head==null){
            head=new Node(x,x);
        }else{
            Node n=new Node(x,Math.min(x,head.min));
            n.next=head;
            head=n;
        }

    }

    public void pop() {
        if(head!=null)
            head=head.next;
    }

    public int top() {
        if(head!=null){
            return head.value;
        } else{
            return -1;
        }
    }

    public int getMin() {
        if(head!=null){
            return head.min;
        }
        else return -1;
    }
}



在这里插入图片描述
结语:
晚安!晚安!晚安!晚安!晚安!晚安!晚安!晚安!晚安!晚安!晚安!

本文地址:https://blog.csdn.net/weixin_44337475/article/details/107396915

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网