public static void removeMin(Stack<Integer> st)
{
if (st.isEmpty())
return;
int min = st.pop();
removeMin(st);
if(min<st.top())
return;
st.push(min);
}
我試圖找到最小元素并將其洗掉,但不幸的是我做不到。我想得到一些幫助,這是我的代碼。
我在類堆疊中只有這些方法:equals、isEmpty、pop、push、top、toString(主要方法)。
提前致謝。
uj5u.com熱心網友回復:
我測驗了你的方法。你有兩行轉置。您需要做的就是在測驗之后進行遞回呼叫。
public static void removeMin(Stack<Integer> st) {
if (st == null || st.isEmpty())
return;
int min = st.pop();
if(st.isEmpty() || min<st.firstElement())
return;
removeMin(st); // this was in the wrong place, causing the stack to empty out completely
st.push(min);
}
我運行了這個例子:
public static void main (String[] args) {
Stack<Integer> stack = new Stack<>();
stack.add(2);
stack.add(1); // to be removed
stack.add(5);
stack.add(3);
stack.add(4);
removeMin(stack);
System.out.println(stack.toString());
}
它列印出來了[2, 5, 3, 4]。
此解決方案適用于位于堆疊頂部、底部或任何中間位置的最小值。
uj5u.com熱心網友回復:
您必須將堆疊的頂部與堆疊其余部分的最小元素進行比較。
那不是你在做什么。您只是將堆疊的頂部與堆疊的下一個元素進行比較。
您可能應該更改遞回方法以回傳最小元素。這樣你可以比較它:
public static int removeMin(Stack<Integer> st)
{
if (st.isEmpty())
return Integer.MAX_VALUE; // if the stack is empty, return a value that is larger
// than any other value
int top = st.pop();
int min = removeMin(st);
if(top < min) {
// top is the minimum element
st.push(min);
return top;
} else {
// min is the minimum element
st.push(top);
return min;
}
}
我沒有測驗過。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/435062.html
