Min Stack
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,pop,top,并同时能获取栈元素的最小值。
push(x)–压栈
pop()–出栈
top()–获取栈顶元素
getMin()–获取栈的最小元素
解题思路:要求压栈、出栈、寻找栈中最小值的时间复杂度都是O(1),所以按照网友博客给的资料需要申请两个栈,一个用于正常的存储数据(data数组),另一个用于存储最小值(min数组),并设置相应两个栈的栈顶指针,对于压栈和出栈的时间复杂度当然是O(1),但难点在getMin获取栈的最小值,若使用一般的求数组的最小值算法,其时间复杂度为O(n),所以不符合题意对于min数组用于存储data栈的最小值,当push数据进data数组时同时和min数组的栈顶元素进行比较,若大于min的栈顶元素则不压入min数组内,否则同时压入min数组中,这样getMin()就直接从min数组中的栈顶读取,时间复杂度为O(1)。
难点:不容易想到用两个栈来存储数据,一个用于正常的存储栈数据,,另一个用于存储前一个栈的最小值。
实现C代码: