voidpop(){ int t = diff.top(); diff.pop(); if (t < 0) { //更新最小值 minE = minE - t; } }
inttop(){ int t = diff.top(); if (t >= 0) { return t + minE; } else { return minE; } }
intmin(){ return minE; }
//O(1)额外空间的解法【注意:下面的代码可能有错误!调试未通过!】
stack<int> diffs; int m = MAX_INT;
voidpush(int x){
if (diffs.empty()) { m = x; diffs.push(0); return; }
diffs.push(m - x); if (x > m) { m = x; } } voidpop(){ int s = diffs.top(); if (s < 0) { m = m + s; //更新max } diffs.pop(); } inttop(){ int s = diffs.top(); return m - s; } intgetMax(){ return m; }
};
/** * 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.getMin(); */