(LeetCode) 155. Min Stack

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 element val onto 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2

Constraints

  • -^231 <= val <= 2^31 - 1
  • Methods pop, top and getMin operations will always be called on non-empty stacks.
  • At most 3 * 10^4 calls will be made to push, pop, top, and getMin.

Solution

Exapnder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class MinStack() {

/** initialize your data structure here. */
var stack = Stack<Int>()

fun push(`val`: Int) {
stack.push(`val`)
}

fun pop() {
stack.pop()
}

fun top(): Int {
return stack.peek()
}

fun getMin(): Int {
return stack.toList().min()!!
}

}

/**
* Your MinStack object will be instantiated and called as such:
* var obj = MinStack()
* obj.push(`val`)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/

Point of Thinking

  • stack collection으로 편하게 구현했다.
  • 디자인 조건의 top()peek()으로 대응하면 된다.
  • getMin()은 list로 변환한 후 min()으로 추출하면 된다.
  • min() 함수는 deprecated되어서 minOrNull()을 써야하지만, leetcode에서 지원하지 않으므로 min을 선택하였다.
  • min()을 쓰면 Int?을 반환하여 !!를 사용했지만, 문제 조건상 getMin()호출시 stack은 비어있지않으므로 Accepted에는 지장이 없다.