Created
July 3, 2014 03:02
-
-
Save nealhu/9fd25a583db13d4e7647 to your computer and use it in GitHub Desktop.
CC_3_2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Cracking the Coding Interview | |
// 3.2 How would you design a stack which, in addition to push and pop, | |
// also has a function min which returns the minimum element? | |
// Push, pop and min should all operate in O(1) time. | |
import java.util.Stack; | |
class MinStack { | |
private Stack<Integer> s; | |
private Stack<Integer> minValues; | |
public MinStack() { | |
s = new Stack<Integer>(); | |
minValues = new Stack<Integer>(); | |
} | |
public void push(Integer element) { | |
s.push(element); | |
if (minValues.empty() || element <= minValues.peek()) { | |
minValues.push(element); | |
} | |
s.push(element); | |
} | |
public Integer pop() { | |
if (minValues.peek() < s.peek()) { | |
return s.pop(); | |
} else { | |
minValues.pop(); | |
return s.pop(); | |
} | |
} | |
public Integer min() { | |
return minValues.peek(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment