Skip to content

Instantly share code, notes, and snippets.

@qingl97
Created July 6, 2016 12:10
Show Gist options
  • Save qingl97/640f73b420f14aa8b5110846d4e2fb99 to your computer and use it in GitHub Desktop.
Save qingl97/640f73b420f14aa8b5110846d4e2fb99 to your computer and use it in GitHub Desktop.
public class MinStack {
private List<Integer> data;
private int top_idx;
/** initialize your data structure here. */
public MinStack() {
data = new ArrayList<Integer>();
top_idx = -1;
}
public void push(int x) {
top_idx++;
data.add(top_idx, x);
}
public void pop() {
data.remove(top_idx);
top_idx--;
}
public int top() {
return data.get(top_idx);
}
public int getMin() {
if(top_idx < 0) throw new RuntimeException("no elements in stack");
int min = data.get(0);
for(int i=0; i<= top_idx; i++) {
min = Math.min(min, data.get(i));
}
return min;
}
}
/**
* 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();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment