點(diǎn)擊進(jìn)入 ??途W(wǎng)題庫(kù):包含min函數(shù)的棧
題目描述
定義棧的數(shù)據(jù)結(jié)構(gòu),請(qǐng)?jiān)谠擃愋椭袑?shí)現(xiàn)一個(gè)能夠得到棧中所含最小元素的min函數(shù)(時(shí)間復(fù)雜度應(yīng)為O(1))。
注意:保證測(cè)試中不會(huì)當(dāng)棧為空的時(shí)候,對(duì)棧調(diào)用pop()或者min()或者top()方法。
方法一 解法不滿足題目要求,不過(guò)獲取正確數(shù)據(jù)
import java.util.Stack;
/**
* 我這個(gè)時(shí)間復(fù)雜度有問(wèn)題,有個(gè)o(n)在里頭,就是
* 那個(gè)findMin是個(gè)o(n)的復(fù)雜度
*
*/
public class Solution {
private Stack<Integer> stack;
private int min;
public Solution() {
stack = new Stack<Integer>();
}
public void push(int node) {
stack.push(node);
if(stack.size() == 1) {
min = node;
} else {
findMin();
}
}
private void findMin() {
//如果值小于等于的時(shí)候,每次要找出其中的最小值
min = stack.get(0);
for(int i = 1; i < stack.size(); i++) {
min = Math.min(stack.get(i), min);
}
}
public void pop() {
int popValue = stack.pop();
if(stack.size() == 1) {
min = stack.get(0);
} else {
if(popValue <= min) {
findMin();
} else {
//值不受影響
}
}
}
public int top() {
int popValue = stack.pop();
if(stack.size() == 1) {
min = stack.get(0);
} else {
if(popValue <= min) {
findMin();
} else {
//值不受影響
}
}
return popValue;
}
public int min() {
return min;
}
}
方法二 (借用第二個(gè)棧,輔助空間解決)
import java.util.Stack;
public class Solution {
private Stack<Integer> stack;
private Stack<Integer> stack2;
private int min;
public Solution() {
stack = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void push(int node) {
stack.push(node);
if(stack2.isEmpty()) {
stack2.push(node);
} else {
if(stack2.peek() >= node) {
stack2.push(node);
}
}
}
public void pop() {
int popValue = stack.pop();
if(popValue == stack2.peek()) {
stack2.pop();
}
}
public int top() {
return stack.peek();
}
public int min() {
return stack2.peek();
}
}