155. Min Stack
- Explore : Interview > Top Interveiw Questions > Easy Collection
- 분류 : Design
- 난이도 : Easy
Problem
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack()initializes the stack object.void push(val)pushes the elementvalonto the stack.void pop()removes the element on the top of the stack.int top()gets the top element of the stack.int getMin()retrieves the minimum element in the stack.
Example 1
1 | Input |
Constraints
-^231 <= val <= 2^31 - 1- Methods
pop,topandgetMinoperations will always be called on non-empty stacks. - At most
3 * 10^4calls will be made topush,pop,top, andgetMin.
Solution
Exapnder
1 | class MinStack() { |
Point of Thinking
- stack collection으로 편하게 구현했다.
- 디자인 조건의
top()은peek()으로 대응하면 된다. getMin()은 list로 변환한 후min()으로 추출하면 된다.min()함수는 deprecated되어서minOrNull()을 써야하지만, leetcode에서 지원하지 않으므로 min을 선택하였다.min()을 쓰면Int?을 반환하여!!를 사용했지만, 문제 조건상getMin()호출시 stack은 비어있지않으므로 Accepted에는 지장이 없다.
