包含min函數的棧
題目:
定義棧的數據結構,請在該類型中實現一個能夠得到棧中所含最小元素的min函數(時間複雜度應爲O(1))。
注意:保證測試中不會當棧爲空的時候,對棧調用pop()或者min()或者top()方法。
代碼:
package com.sjsq.test;
/**
* @author shuijianshiqing
* @date 2020/5/22 22:20
*/
import java.util.Stack;
/**
* 定義棧的數據結構,請在該類型中實現一個能夠得到棧中所含最小元素
* 的min函數(時間複雜度應爲O(1))。
* 注意:保證測試中不會當棧爲空的時候,對棧調用pop()或者min()或者top()方法。
*/
public class Solution {
Stack<Integer> stack = new Stack<Integer>();
// 設置一個臨時棧來存放被pop出的數據
Stack<Integer> tmp = new Stack<Integer>();
public void push(int node) {
stack.push(node);
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
int min = Integer.MAX_VALUE;
// 出棧
while(stack.isEmpty() != true){
int node = stack.pop();
if(min > node){
min = node;
}
tmp.push(node);
}
// 進棧
while(tmp.isEmpty() != true){
stack.push(tmp.pop());
}
return min;
}
}