문제
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 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.
You must implement a solution with O(1) time complexity for each function.
예시
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
조건
- -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.
답
두 개의 스택을 함께 사용합니다.
첫 번째 스택 stack은 일반적인 값을 담는 용도로,
두 번째 스택 minStack은 첫 번째 스택에 값들이 담겼을 때의 최솟값을 기록하는 용도로 사용합니다.
하여 stack에 값이 들어갈 때마다 그 때의 최솟값을 minStack에 저장하고,
반대로 값이 나갈 때마다는 minStack에서도 값을 빼주면 됩니다.
MinStack( )
var MinStack = function() {
this.stack = [];
this.minStack = [];
};
MinStack.push( )
/**
* @param {number} val
* @return {void}
*/
MinStack.prototype.push = function(val) {
this.stack.push(val);
if (this.minStack.length === 0) {
this.minStack.push(val);
}
else {
const curMin = this.minStack[this.minStack.length - 1];
this.minStack.push((curMin > val)? val : curMin);
}
};
MinStack.pop( )
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.minStack.pop()
return this.stack.pop()
};
MinStack.top( )
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length-1]
};
MinStack.getMin( )
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.minStack[this.minStack.length-1]
};728x90
'CS > PS' 카테고리의 다른 글
| [PS] NYPC | 2515. 잃어버린 섬 여행 (0) | 2025.09.17 |
|---|---|
| [PS] NYPC | 2513. 등차수열 (0) | 2025.09.17 |
| [PS] Leet | 146. LRU 캐시 (1) | 2025.08.18 |
| [PS] Leet | 295. 데이터 스트림에서 중간값 찾기 (2) | 2025.08.06 |
| [PS] Leet | 212. 단어 찾기 II (2) | 2025.07.25 |