[Medium] 155. Min Stack

문제

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(int 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.

You must implement a solution with O(1) time complexity for each function.

 

일정한 시간에 최소 값을 푸시, 팝, 상단 및 검색할 수 있는 스택을 설계합니다.


MinStack 클래스 구현:

MinStack()은 스택 개체를 초기화합니다.
void push() 는 val를 스택 위로 밀어 올립니다.
void pop removes() 은 스택의 맨 위에 있는 요소를 제거합니다.
int top() 는 스택의 최상위 요소를 가져옵니다.
int getMin()은 스택의 최소 값을 검색합니다.
각 함수에 대해 O(1) 시간 복잡도를 갖는 솔루션을 구현해야 합니다.

 

예시

Example 1:

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 <= 231 - 1
  • Methods pop, top and getMin operations will always be called on non-empty stacks.
  • At most 3 * 104 calls will be made to push, pop, top, and getMin.

 

해결 코드

var MinStack = function() {
  this.elements = [];
};

/**

 @param {number} x
 @return {void}
 */
MinStack.prototype.push = function(x) {
  this.elements.push({
    value: x,
    min: this.elements.length === 0 ? x : Math.min(x, this.getMin()),
  });
};
/**

 @return {void}
 */
MinStack.prototype.pop = function() {
  this.elements.pop();
};
/**

 @return {number}
 */
MinStack.prototype.top = function() {
  return this.elements[this.elements.length - 1].value;
};
/**

 @return {number}
 */
MinStack.prototype.getMin = function() {
  return this.elements[this.elements.length - 1].min;
};

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

'leetCode' 카테고리의 다른 글

[Medium] 707. Design Linked List  (0) 2022.07.28
[Medium] 1797. Design Authentication Manager  (0) 2022.07.28
[Medium] 1845. Seat Reservation Manager  (0) 2022.07.26
[Easy] 860. Lemonade Change  (0) 2022.07.26
[Medium] 2. Add Two Numbers  (0) 2022.07.19