题目描述:
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
思路:
主要是min方法的实现,直接遍历栈,返回最小值即可。(注意方法的时间复杂度)
代码实现:
var stack = [];
function push(node)
{
// write code here
return stack.push(node);
}
function pop()
{
// write code here
stack.pop();
}
function top()
{
// write code here
return stack.pop();
}
function min()
{
// write code here
var minNum=stack[0];
for (var i=1;i<stack.length;i++){
if (stack[i]<minNum){
minNum = stack[i];
}
}
return minNum;
}