題目參考鏈接:劍指 Offer 30. 包含min函數(shù)的棧 - 力扣(LeetCode) (leetcode-cn.com)
原先寫的代碼湿蛔,用list來寫孙乖,有兩個用例通不過
class MinStack {
List<Integer> list1;
List<Integer> list2;
static int min_num = 10000;
/** initialize your data structure here. */
public MinStack() {
list1 = new ArrayList<>();
list2 = new ArrayList<>();
}
public void push(int x) {
list1.add(x);
if(list2.isEmpty())
list2.add(x);
else if(x <= list2.get(list2.size()-1))
list2.add(x);
}
public void pop() {
if(list2.get(list2.size() - 1) == list1.get(list1.size()-1)){ //這一步錯了
list1.remove(list1.size()-1);
list2.remove(list2.size()-1);
}
else list1.remove(list1.size() - 1);
}
public int top() {
return list1.get(list1.size()-1);
}
public int min() {
return list2.get(list2.size()-1);
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.min();
*/
錯誤原因:Integer雖然可以自動拆箱,但是這個自動拆箱是有范圍的奶是,根據(jù)java1.8的源碼,范圍是-127~128,此范圍可以用==判斷兩個值是否相等,但是本題中用例數(shù)據(jù)超出這個范圍(如-1024和512)就不能實現(xiàn)自動拆箱弦牡,這就是以上代碼無法通過較大數(shù)據(jù)用例的原因。
改進(jìn)方案漂羊,可以將==
替換為equals()
函數(shù)