leetcode学习打卡--155. 最小栈(水题-三种解法 蛮力数组搜/指针/辅助栈)

155.最小栈

设计一个支持 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 操作总是在 非空栈 上调用。

其实就是实现一个能获取最小值的栈。
蛮力搜索其实也能过,目前最大数据也只是8000个不到的操作吧,直接开10000的数组存就完事。

蛮力数组搜索

class MinStack {
public:
    int len=0; //长度
    int mystack[10100];
    /** initialize your data structure here. */
    MinStack() {
       len=0; //长度
        for(int i=0;i<10100;i++)
        mystack[i]=0;
    }
    void push(int x) {
        if(x)
        mystack[len]=x;
        len++;
    }   
    void pop() {
        mystack[len]=NULL;
        len--;
    }    
    int top() {
       return mystack[len-1];
    }   
    int getMin() {
        int res=INT_MAX;
        for(int i=0;i<len;i++)
        if(mystack[i]<res) res=mystack[i];
        return res;
    }
};


指针法–每个节点都存val与当前最小val,空间换时间

class MinStack {
private:
	struct Node {
		int val=0;
		int min=INT_MAX;
		Node *next=NULL;
	};
public:
    Node *head = new Node;
	void push(int x) {
		Node *node = new Node;
		node->val = x;
		node->min = head->min < x ? head->min : x;
		node->next = head;
		head = node;
	}
	void pop() {
		head = head->next;
	}
	int top() {
		return head->val;
	}
	int getMin() {
		return head->min;
	}
};

辅助栈–用第二个栈来存储最小值,空间换时间避免蛮力搜

class MinStack {
public:
    stack<int> num_stack;
    stack<int> min_stack;
    /** initialize your data structure here. */
    MinStack() {
      min_stack.push(INT_MAX); 
    }
    
    void push(int x) {
        num_stack.push(x);
        if(x<min_stack.top())
        min_stack.push(x);
        else
        min_stack.push(min_stack.top());
    }
    
    void pop() {
        num_stack.pop();
        min_stack.pop();
    }
    
    int top() {
        return num_stack.top();
    }
    
    int getMin() {
        return min_stack.top();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值